0 votes
1 view
in Python by (9.3k points)

In the library, whether the list of python builtins and python reserved words available? 

I just want to do something like this below:

 from x.y import reserved_words_and_builtins

 if x in reserved_words_and_builtins:

     x += '_'

1 Answer

0 votes
by (19.3k points)

You can utilize keyword.iskeyword to check that the string is a keyword. Moreover, you can also use keyword.kwlist to get the list of reserved keywords.

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

You can check the builtins module, if you would like to include the built-in names as well,

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

In case of python 2, you have to use this __builtin__ module

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

Want to become a expert in python? Join the python course fast!

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...