9

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")
Prog1020
  • 4,530
  • 8
  • 31
  • 65

2 Answers2

10
if 'c' in locals():
    print ('Ok')
else:
    print('no')

If you need to check for global use globals() instead

Dennis Sakva
  • 1,447
  • 2
  • 13
  • 26
3

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

mdeous
  • 17,513
  • 7
  • 56
  • 60
  • 1
    Unfortunately this doesn't work if c is set to None. – awatts Jan 20 '23 at 12:01
  • @awatts indeed, good point. If you know in advance what types are expected to be found then adding a call to `isinstance()` could help, but I believe the selected answer is best for most cases (and more readable). – mdeous Jan 22 '23 at 12:46