Source From Here
Question
I want to check if a variable exists. Now I'm doing something like this:
Are there other ways without exceptions?
How-To
To check the existence of a local variable:
To check the existence of a global variable:
To check if an object has an attribute:
Supplement
* Python built-in Functions - globals()
* Python built-in Functions - locals()
Question
I want to check if a variable exists. Now I'm doing something like this:
- try:
- myVar
- except NameError:
- # Do something.
How-To
To check the existence of a local variable:
- if 'myVar' in locals():
- # myVar exists.
- pass
- if 'myVar' in globals():
- # myVar exists.
- pass
- if hasattr(obj, 'attr_name'):
- # obj.attr_name exists.
- pass
* Python built-in Functions - globals()
* Python built-in Functions - locals()
沒有留言:
張貼留言