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.


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...