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.
You can delete a global name x
using
del x
Python doesn't 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 doesn't necessarily remove the object the name pointed to.
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.