Python 3中的True、False、None是关键字还是内置对象?
在Python 2里,这个问题很明确。但是在Python 3中,我有点困惑。
>>> import builtins
>>> dir(builtins)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
>>> import keyword
>>> dir(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
True、False和None在builtins模块和keywords模块中都有。那么我应该怎么理解它们呢?是把它们当作内置类,还是当作关键字?
1 个回答
10
它们是保留字和内置值。从Python 3 新特性中可以看到:
True
、False
和None
是保留字。(在2.6版本中,已经部分限制了对None
的使用。)
这意味着你不能把它们当作变量名,也不能给它们赋其他值。这是为了防止不小心覆盖这些内置的单例值:
>>> True = False
File "<stdin>", line 1
SyntaxError: can't assign to keyword
另外,可以看看Guido van Rossum关于None
、True
和False
的历史讲解:
我还是忘了回答
None
、True
和False
是字面量还是关键字。我的回答是它们都是。它们是关键字,因为解析器是这样识别它们的。它们是字面量,因为在表达式中它们的作用是代表常量值。
由于True
、False
和None
被归类为关键字,Python编译器实际上可以优化它们的使用,因为你不能(直接)重新绑定这些名字。Python可以把它们当作常量来查找,而不是全局变量,这样速度更快。
在Python 3.4之前,仍然有一些特殊情况会导致编译器对这些对象进行全局查找,具体可以查看问题16619。从Python 3.4开始,Python解析器被扩展,增加了一个新的AST节点NameConstant
,以确保它们在任何地方都被视为常量。