如何将Python变量设置为'未定义'?

36 投票
7 回答
152131 浏览
提问于 2025-04-18 07:23

在Python 3中,我有一个全局变量,最开始是“未定义”的状态。

然后我把它设置成了某个值。

有没有办法把这个变量恢复到“未定义”的状态呢?

@martijnpieters

编辑 - 这段代码展示了一个全局变量是如何开始于未定义状态的。

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
>>> 

7 个回答

3

这里有一种情况,你实际上需要使用 undef:就是函数的参数可以接受任何值(包括 None),但我们仍然需要知道这个值是否被提供过。

举个例子:

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

这和 dict.pop 很像,你需要知道是否给了 default。虽然可以用 *args, **kwargs 来模拟,但这样会变得很复杂,而有 undef 就能大大简化这个过程。

在我看来,最简单的方法是这样的:

_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

前面的下划线表示这个变量是模块内部的私有变量,不应该在外部使用,这也说明 _undef 不应该作为参数值使用,这样就能很好地检测出“这个值是未定义的”。

3

根据提问者的评论:

# check if the variable is undefined
try:
    x
# if it is undefined, initialize it
except NameError:
    x = 1

就像其他人说的,你可以使用 del 这个关键词来删除一个已经定义的变量。

10

如果你想测试它的“未定义状态”,你应该把它设置为 None:

variable = None

然后用下面的方式进行测试:

if variable is None: 

如果你想清理一些东西,可以删除它,使用 del variable,但这本来应该是垃圾回收器的工作。

59

你可能想把它设置为 None。

variable = None

检查变量是否“定义过”。

is_defined = variable is not None

你可以删除这个变量,但这样做其实不太符合 Python 的风格。

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')

遇到 NameError(名字错误)并处理它并不是很常见,所以通常更推荐把变量设置为 None。

35

你可以用下面的方式删除一个全局变量 x

del x

在Python中,变量的概念和C或Java不太一样。Python里的变量其实就是一个标签,你可以把它贴在任何对象上,而不是指向某个固定的内存位置。

删除变量并不一定会把它指向的对象也删除掉。

撰写回答