Danh sách các từ và nội dung dành riêng của Python có sẵn trong thư viện không?


135

Danh sách các từ và nội dung dành riêng của Python có sẵn trong thư viện không? Tôi muốn làm một cái gì đó như:

 from x.y import reserved_words_and_builtins

 if x in reserved_words_and_builtins:
     x += '_'

có thể trùng lặp Danh sách các từ khóa python
Abhijit

3
@Abhijit: Sự khác biệt chính là tôi đã yêu cầu tất cả các từ dành riêng bao gồm cả các từ dựng sẵn.
Neil G

chỉnh sửa: rõ ràng nhiều người sử dụng "từ dành riêng" để đồng nghĩa với từ khóa. Tôi đã chỉnh sửa câu hỏi tương ứng.
Neil G

@NeilG Tôi khá chắc chắn rằng chúng là từ đồng nghĩa trong Python. Nội dung chắc chắn không phải là từ dành riêng, vì chúng có thể được gán lại, ví dụ print = None.
wjandrea

Câu trả lời:


198

Để xác minh rằng một chuỗi là một từ khóa bạn có thể sử dụng keyword.iskeyword; để có được danh sách các từ khóa dành riêng bạn có thể sử dụng keyword.kwlist:

>>> import keyword
>>> keyword.iskeyword('break')
True
>>> 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']

Nếu bạn muốn bao gồm tích hợp tên cũng như (Python 3), sau đó kiểm tra các builtinsmô-đun :

>>> 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', 'RecursionError', 'ReferenceError',
 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration',
 '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']

Đối với Python 2 bạn sẽ cần phải sử dụng các __builtin__mô-đun

>>> import __builtin__
>>> dir(__builtin__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']

11
Lưu ý rằng trong python2.6 <= xy <3.0 Nonekhông chính thức một từ khóa (theo kwlistiskeyword) nhưng nó thực sự là một từ khóa (vì None = 1không thành công với một SyntaxError), mặc dù nó được liệt kê như là built-in cùng với TrueFalse.
Bakuriu

3
Vì tò mò, lý do triết học nào để có sự phân biệt giữa từ khóa và nội dung? Không phải tất cả họ chỉ nên được bảo lưu?
gây nhầm lẫn vào

11
@ chú ý: từ khóa là một phần của ngữ pháp ngôn ngữ. Nội dung hoạt động như thể bạn đã làm from builtins import *; chúng có thể bị ghi đè.
Neil G

2
@ chú ý: Cụ thể, giảm thiểu từ khóa có nghĩa là các từ phổ biến không cần thiết không có sẵn trong các tình huống an toàn . Chắc chắn, gán set = 1là một ý tưởng tồi tệ, nhưng một lớp với một phương thức hoặc thuộc tính được đặt tên set(vì vậy nó luôn được tham chiếu với instance.set, không đơn giản set) không nhất thiết phải khủng khiếp. Có những trường hợp hoàn toàn hợp pháp để đặt tên cho một phương pháp set; nếu setlà một từ khóa, bạn không thể làm điều đó.
ShadowRanger

1
@wwii Tên phương thức đặc biệt không được xác định toàn cầu như nội dung hoặc một phần của cú pháp như từ khóa. __len__trên chính nó có nghĩa là không có gì. Bạn phải nói str.__len__hay list.__len__. Vì vậy, không có lo lắng về tên biến của bạn va chạm với chúng.
Nick S
Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.