程式扎記: [ Python 常見問題 ] How do I check if a variable exists in Python?

標籤

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.


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!