라이브러리에서 파이썬 예약어 및 내장 목록을 사용할 수 있습니까?


135

라이브러리에서 파이썬 예약어 및 내장 목록을 사용할 수 있습니까? 나는 다음과 같은 것을하고 싶다 :

 from x.y import reserved_words_and_builtins

 if x in reserved_words_and_builtins:
     x += '_'


3
@ Abhijit : 주요 차이점은 내장 단어를 포함한 모든 예약어를 요구한다는 것입니다.
Neil G

편집 : 분명히 많은 사람들이 "예약어"를 사용하여 키워드와 동의어입니다. 그에 따라 질문을 편집했습니다.
Neil G

@NeilG 나는 그들이 파이썬에서 동의어라고 확신합니다. 예를 들어, 내장은 재배치 될 수 있기 때문에 예약어가 아닙니다 print = None.
wjandrea

답변:


198

문자열이 키워드인지 확인하기 위해 사용할 수 있습니다 keyword.iskeyword. 사용할 수있는 예약 키워드 목록을 얻으려면 다음을 사용하십시오 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']

내장 이름도 포함하려면 (Python 3) 모듈 을 확인 하십시오builtins .

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

Python 2의 경우 모듈 을 사용해야 합니다.__builtin__

>>> 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
python2.6에서 <= XY <3.0 참고 None하지 (에 따라 공식적으로 키워드 kwlistiskeyword) 그러나 그것은 이다 (때문에 실제로 키워드 None = 1실패 SyntaxError내장으로 함께가 나열되어 있지만,) TrueFalse.
Bakuriu

3
호기심에서 키워드와 내장을 구별하는 철학적 정당성은 무엇입니까? 모두 예약되어 있지 않아야합니까?
22:16에

11
@notconfusing : 키워드는 언어 문법의 일부입니다. 내장은 마치 마치 마치 마치 행동합니다 from builtins import *. 재정의 될 수 있습니다.
Neil G

2
@notconfusing : 특히 키워드를 최소화하면 안전한 시나리오 에서 일반적인 단어를 불필요하게 사용할 수 없습니다 . 물론 할당 set = 1은 끔찍한 아이디어이지만 이름이 지정된 메소드 또는 속성을 가진 클래스 set(항상 instance.set평범하지 않고 항상 참조 됨 set)는 반드시 끔찍한 것은 아닙니다. 메소드의 이름을 짓는 데는 완전히 합법적 인 경우가 있습니다 set. 경우 set키워드했다, 당신은 할 수 없었다.
ShadowRanger

1
@wwii 특수 메소드 이름은 내장과 같이 전역 적으로 정의되지 않거나 키워드와 같은 구문의 일부가 아닙니다. __len__그 자체로는 아무 의미가 없습니다. 당신은 말을 str.__len__하거나 list.__len__. 따라서 변수 이름과 충돌 할 염려가 없습니다.
Nick S
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.