2015年9月15日 星期二

[ Python 常見問題 ] How do I check if a variable exists in Python?

Source From Here
Question
I want to check if a variable exists. Now I'm doing something like this:
  1. try:  
  2.    myVar  
  3. except NameError:  
  4.    # Do something.  
Are there other ways without exceptions?

How-To
To check the existence of a local variable:
  1. if 'myVar' in locals():  
  2.   # myVar exists.  
  3.   pass  
To check the existence of a global variable:
  1. if 'myVar' in globals():  
  2.   # myVar exists.  
  3.   pass  
To check if an object has an attribute:
  1. if hasattr(obj, 'attr_name'):  
  2.   # obj.attr_name exists.  
  3.   pass  
Supplement
Python built-in Functions - globals()
Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).

Python built-in Functions - locals()
Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks.


沒有留言:

張貼留言

[ Java 文章收集 ] 局部敏感哈希 (Locality-Sensitive Hashing, LSH) 方法介紹

Source From  Here   Preface   本文主要介紹一種用於海量高維數據的近似最近鄰快速查找技術—— 局部敏感哈希  ( Locality-Sensitive Hashing, LSH ),內容包括了 LSH 的原理、LSH 哈希函數集、以及 LSH 的一...