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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)