backend/python

python: check if variable exists in python

seul chan 2018. 5. 11. 20:19

1. check if variable is in local

if 'my_var' in locals():

2. check if variable is in global

if 'my_var' in global():

3. check if object has attribute

if hasattr(obj, 'attr_name'):

4. try/except

try:
    my_var
except NameError:
    my_var = 'test'