How to set a Python variable to 'undefined'?
Question:
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
>>>
Answers:
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.
You can also define your var x as None
x = None
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.
In light of the OP’s comments:
# check if the variable is undefined
try:
x
# if it is undefined, initialize it
except NameError:
x = 1
And like the rest said, you can delete a defined variable using the del
keyword.
Here is a case when you actually want undef
: function arguments that can have any value (including None
), but we still need to know if the value was provided or not.
For example:
class Foo:
"""
Some container class.
"""
def pop(self, name, default):
"""
Delete `name` from the container and return its value.
:param name: A string containing the name associated with the
value to delete and return.
:param default: If `name` doesn't exist in the container, return
`default`. If `default` is not given, a `KeyError` exception is
raised.
"""
try:
return self._get_and_delete_value_for(name)
except GetHasFailedError:
if default is undefined:
raise KeyError(name)
else:
return default
This is very much like dict.pop
, and you need to know if default
was given. One could fake that with *args, **kwargs
, but that gets messy quickly, and having undef
would really help.
IMO, the easiest approach for that is this:
_undef = object()
class Foo:
"""
Some container class.
"""
def pop(self, name, default=_undef):
"""
Delete `name` from the container and return its value.
:param name: A string containing the name associated with the
value to delete and return.
:param default: If `name` doesn't exist in the container, return
`default`. If `default` is not given, a `KeyError` exception is
raised.
"""
try:
return self._get_and_delete_value_for(name)
except GetHasFailedError:
if default is _undef:
raise KeyError(name)
else:
return default
The leading underscore implies that the variable is private to the module and shouldn’t be used outside of it, which suggests that _undef
should not be used as an argument value, making it a good detector for "this value is undefined".
Use this:
undefined = "undefined"
# del x isn't effective, so use "x = undefined"
x = 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
>>>
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.
You can also define your var x as None
x = None
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.
In light of the OP’s comments:
# check if the variable is undefined
try:
x
# if it is undefined, initialize it
except NameError:
x = 1
And like the rest said, you can delete a defined variable using the del
keyword.
Here is a case when you actually want undef
: function arguments that can have any value (including None
), but we still need to know if the value was provided or not.
For example:
class Foo:
"""
Some container class.
"""
def pop(self, name, default):
"""
Delete `name` from the container and return its value.
:param name: A string containing the name associated with the
value to delete and return.
:param default: If `name` doesn't exist in the container, return
`default`. If `default` is not given, a `KeyError` exception is
raised.
"""
try:
return self._get_and_delete_value_for(name)
except GetHasFailedError:
if default is undefined:
raise KeyError(name)
else:
return default
This is very much like dict.pop
, and you need to know if default
was given. One could fake that with *args, **kwargs
, but that gets messy quickly, and having undef
would really help.
IMO, the easiest approach for that is this:
_undef = object()
class Foo:
"""
Some container class.
"""
def pop(self, name, default=_undef):
"""
Delete `name` from the container and return its value.
:param name: A string containing the name associated with the
value to delete and return.
:param default: If `name` doesn't exist in the container, return
`default`. If `default` is not given, a `KeyError` exception is
raised.
"""
try:
return self._get_and_delete_value_for(name)
except GetHasFailedError:
if default is _undef:
raise KeyError(name)
else:
return default
The leading underscore implies that the variable is private to the module and shouldn’t be used outside of it, which suggests that _undef
should not be used as an argument value, making it a good detector for "this value is undefined".
Use this:
undefined = "undefined"
# del x isn't effective, so use "x = undefined"
x = undefined