Search code examples
pythonfunctionvariablesgloballocal

How can i check if there is a global or local variable


I want to check if that variable exists and print it if it does.

x = 10 

def example(): 

z = 5

print("X (Global variable) : ",x) 
print("Z (example() : ",z)

example() 

print(z) 

When i add print(z) it will obviously raises an error because there is no variable called z.

Thanks for the answers guys. (specially Jasper, kevin and icantcode)

x = 10 
def example(): 

z = 5

example() 


try:
    print(z)
except NameError:
    print("There is no global variable called Z! ")

Solution

  • The most straight forward way would be to try to use it and if it fails do something else:

    try:
        something_with(z)
    except NameError:
        fallback_code()
    

    But this could potentially fail because something_with doesn't exist or has a typo/bug in it so the NameError you catch may be unrelated to the z variable.

    you could also check dictionaries of locals() and globals() (and builtins module if you want to go that deep)

    # import builtins
    if 'z' in locals() or 'z' in globals(): # or hasattr(builtins, 'z'):
        print(z)
    else:
        fallback_code()