In Python 3, I have a global variable which starts as "undefined".
I then set it to something.
Is there a way to return that variable to a state of "undefined"?
@martijnpieters
EDIT - this shows how a global variable starts in a state of undefined.
Python 2.7.5+ (default, Feb 27 2014, 19:37:08) [GCC 4.8.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> x Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'x' is not defined >>> global x >>> x Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'x' is not defined >>>
Answer: Use the equality operator ( == )In JavaScript if a variable has been declared, but has not been assigned a value, is automatically assigned the value undefined . Therefore, if you try to display the value of such variable, the word "undefined" will be displayed.
An undefined variable in the source code of a computer program is a variable that is accessed in the code but has not been declared by that code. In some programming languages, an implicit declaration is provided the first time such a variable is encountered at compile time.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With