I want to check is name "my_name" (which is my class object) defined already. How can I do it w/out using try-except:
try:
if c:
print("ok")
except NameError:
print("no")
if 'c' in locals():
print ('Ok')
else:
print('no')
If you need to check for global use globals() instead
If you don't want to use try
/except
, you could lookup the locals()
and globals()
. Such a check would look like:
if locals().get('c', globals().get('c')) is None:
print "no"
else:
print "ok"
The call in the if
condition would lookup the local variables first, and if your variable isn't found there, would then lookup global variables. If the variable isn't found in one or the other, None
is returned