How to set a Python variable to undefined?

How to set a Python variable to undefined?

You probably want to set it to None.

variable = None

Check if variable is defined

is_defined = variable is not None

You could delete the variable, but it is not really pythonic.

variable = 1
del variable
try:
    print(variable)
except (NameError, AttributeError):
    # AttributeError if you are using del obj.variable and print(obj.variable)
    print(variable does not exist)

Having to catch a NameError is not very conventional, so setting the variable to None is typically preferred.

You can delete a global name x using

del x

Python doesnt have variables in the sense C or Java have. In Python, a variable is just a tag you can apply to any object, as opposed to a name refencing some fixed memory location.

Deleting doesnt necessarily remove the object the name pointed to.

How to set a Python variable to undefined?

If you want to be able to test its undefined state, you should set it to None :

variable = None

and test with

if variable is None: 

If you want to clean stuff, you can delete it, del variable but that should be task of the garbage collector.

Leave a Reply

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