Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a Python variable to 'undefined'?

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 >>>  
like image 317
Duke Dougal Avatar asked May 23 '14 11:05

Duke Dougal


People also ask

How do you declare an undefined variable?

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.

What does it mean when a variable is undefined in Python?

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.


Video Answer


1 Answers

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.

like image 110
justengel Avatar answered Sep 22 '22 04:09

justengel