Categories
Python Answers

How to check if a variable exists with Python?

Spread the love

Sometimes, we want to check if a variable exists with Python.

In this article, we’ll look at how to check if a variable exists with Python.

How to check if a variable exists with Python?

To check if a variable exists with Python, we can use the locals function to check if a local variables exists.

We can use the globals function to check if a global variable exists.

And we can use hasattr to check if an object has the given attribute.

For instance, we write:

bar = 1


def baz():
    foo = 1
    if 'foo' in locals():
        print('foo exists')


baz()

if 'bar' in globals():
    print('bar exists')


class A:
    attr = 1


obj = A()
if hasattr(obj, 'attr'):
    print('attr exists')

We have the bar global variable.

And we have the baz function with the foo local variable.

In baz, we check if foo is in baz using if 'foo' in locals().

We check if bar is a global variable that’s defined with if 'bar' in globals().

Also, we have an A class with the attr attribute.

We instantiate that and assign the A instance to obj.

Then we check if attr is in obj with if hasattr(obj, 'attr').

Since all of the exist, we should see:

foo exists
bar exists
attr exists

printed.

Conclusion

To check if a variable exists with Python, we can use the locals function to check if a local variables exists.

We can use the globals function to check if a global variable exists.

And we can use hasattr to check if an object has the given attribute.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *