Is the list of Python reserved words and builtins available in a library?
To verify that a string is a keyword you can use keyword.iskeyword
; to get the list of reserved keywords you can use 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']
If you want to include built-in names as well (Python 3), then check the builtins
module:
>>> 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']
For Python 2 you'll need to use the __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']
Python full keywords list
import keyword
print(keyword.kwlist)
lists all the keywords.
In order to get all the built-ins,
import builtins
print(dir(builtins))
gives you all the built-ins:
['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', 'ModuleNotFoundError', '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', 'WindowsError', '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']
Why isn't 'list' a reserved word in Python?
Only keywords are reserved.
list
is not a keyword but a built-in type, as are str
, set
, dict
, unicode
, int
, float
, etc.
There is no point in reserving each and every possible built-in type; python is a dynamic language and if you want to replace the built-in types with a local name that shadows it, you should be able to.
Think of list
and the other types as a pre-imported library of object types; you wouldn't expect defaultdict
from collections
to be reserved either?
Use a static code analyzer to catch errors like these; most IDEs let you integrate one with ease.
Get hints of reserved words in a working IDLE console?
For keywords, you need to put them in quotes (otherwise help(keyword)
would not be a syntactically correct statement).
>>> help('assert')
The "assert" statement
**********************
Assert statements are a convenient way to insert debugging assertions
into a program:
...
You can use the keyword
module to discover what exactly the Python grammar's keywords are.
Is there python code in the Python standard library that uses variable names that shadow builtins?
The builtin I most often shadow is id
, both because it's so useful as a variable name, and the builtin is so rarely called anyway. A quick look in the 2.7 standard library turned up a number of uses:
aifc.py: if id == marker[0]:
aifc.py: id = _read_short(chunk)
aifc.py: if id == self._markers[i][0]:
aifc.py: if id == marker[0]:
difflib.py: id = ' id="%s%s"' % (self._prefix[side],linenum)
difflib.py: id = ''
nntplib.py: id = ''
nntplib.py: id = words[2]
nntplib.py: resp, nr, id = self.statparse(resp)
pdb.py: id = idstring[0].strip()
pdb.py: id = idstring[1].strip()
pdb.py: if id == '': return failed
platform.py: id = values[2]
platform.py: id = ''
platform.py: id = l[1]
platform.py: id = _id
There are plenty of uses of str
, list
, and int
also:
Cookie.py: str = str[1:-1]
mailcap.py: str = os.environ['MAILCAPS']
mimetools.py: str = self.typeheader
mimetools.py: str = 'text/plain'
mimetools.py: str = str[:i]
mimetools.py: str = self.plisttext
mimetools.py: str = str[1:]
mimetools.py: str = str[end:]
rfc822.py: str = m.getheader(name)
rfc822.py: str = m.getrawheader(name)
smtplib.py: str = ""
smtplib.py: str = '%s%s' % (cmd, CRLF)
smtplib.py: str = '%s %s%s' % (cmd, args, CRLF)
sre_parse.py: pattern.str = str
xmllib.py: str = res.group(1)
xmllib.py: str = chr(int(str[2:], 16))
xmllib.py: str = chr(int(str[1:]))
xmllib.py: str = self.entitydefs[str]
xmllib.py: str = '&' + str + ';'
uuid.py: int = long(hex, 16)
uuid.py: int = long(('%02x'*16) % tuple(map(ord, bytes)), 16)
uuid.py: int = ((time_low << 96L) | (time_mid << 80L) |
SimpleHTTPServer.py: list = os.listdir(path)
StringIO.py:list = f.readlines()# list of f.readline() results until EOF
StringIO.py: list = f.readlines()
anydbm.py: list = d.keys() # return a list of all existing keys (slow!)
asynchat.py: self.list = deque()
asynchat.py: self.list = deque(list)
bdb.py: list = self.breaks[filename]
cgi.py: list = None
cgi.py: list = traceback.format_tb(tb, limit) + \
code.py: list = traceback.format_exception_only(type, value)
code.py: list = traceback.format_list(tblist)
dircache.py: cached_mtime, list = cache[path]
dircache.py: cached_mtime, list = -1, []
dircache.py: list = os.listdir(path)
mailbox.py: # list = map(long, filter(pat.match, os.listdir(self.dirname)))
mailbox.py: list = os.listdir(self.dirname)
mailbox.py: list = filter(pat.match, list)
mailbox.py: list = map(long, list)
mhlib.py:list = mh.listfolders() # names of top-level folders
mhlib.py:list = mh.listallfolders() # names of all folders, including subfolders
mhlib.py:list = mh.listsubfolders(name) # direct subfolders of given folder
mhlib.py:list = mh.listallsubfolders(name) # all subfolders of given folder
mhlib.py:list = f.listmessages() # list of messages in folder (as numbers)
mhlib.py:list = f.parsesequence(seq) # parse msgs syntax into list of messages
mhlib.py: list = []
mhlib.py: list = map(int, stuff.split())
multifile.py: list = []
nntplib.py: list = []
nntplib.py: resp, list = self.longcmd('LIST', file)
nntplib.py: resp, list = self.longcmd(line, file)
pickle.py: list = stack[-1]
pickle.py: list = stack[mark - 1]
pipes.py: list = []
poplib.py: list = []; octets = 0
pstats.py: width, list = self.get_print_list(amount)
pstats.py: width, list = self.get_print_list(amount)
pstats.py: width, list = self.get_print_list(amount)
rexec.py: list = []
rfc822.py: list = m.getaddrlist(name)
shelve.py: list = d.keys() # a list of all existing keys (slow!)
socket.py: list = []
telnetlib.py: list = list[:]
traceback.py: list = []
traceback.py: list = []
traceback.py: list = ['Traceback (most recent call last):\n']
traceback.py: list = list + format_tb(tb, limit)
traceback.py: list = []
traceback.py: list = list + format_exception_only(etype, value)
traceback.py: list = []
xdrlib.py: list = []
xdrlib.py: list = []
and there are too many file
and dir
uses to post...
List of python keywords
You are better of using the keyword module
>>> import keyword
>>> keyword.kwlist
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
Is it possible to get a list of keywords in Python?
You asked about statements, while showing keywords in your output example.
If you're looking for keywords, they're all listed in the keyword
module:
>>> import keyword
>>> keyword.kwlist
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif',
'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import',
'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try',
'while', 'with', 'yield']
From the keyword.kwlist
doc:
Sequence containing all the keywords defined for the interpreter. If any keywords are defined to only be active when particular
__future__
statements are in effect, these will be included as well.
Retrieve 'builtins' respectively by their types
IIUC, you could iterate over __builtins__.__dict__
. Though, you'd still need to invert the dictionary after.
d = {k : type(v) for k, v in builtins.__dict__.items()}
d2 = {}
for k, v in d.items():
d2.setdefault(v, []).append(k)
Similar solution with a collections.defaultdict
-
from collections import defaultdict
d = {k : type(v) for k, v in builtins.__dict__.items()}
d2 = defaultdict(list)
for k, v in d.items():
d2[v].append(k)
This happens to be a bit more efficient than the first solution.
Related Topics
Rpy2 Error Wac-A-Mole: R_User Not Defined
Python Interface for R Programming Language
How to Convert R Dataframe Back to Pandas Using Rpy2
Trouble Installing Rpy2 on Win7 (R 2.12, Python 2.5)
How to Connect R Conda Env to Jupyter Notebook
Python(Or Numpy) Equivalent of Match in R
Set Background Color for Subplot
Reduce Number of Levels for Large Categorical Variables
Converting Yes and No to 0 and 1 in R
Is There an R Equivalent of the Pythonic "If _Name_ == "_Main_": Main()"
Creating a List of Dictionaries Results in a List of Copies of the Same Dictionary
Subclassing Tuple with Multiple _Init_ Arguments
Don't Wait for a Page to Load Using Selenium in Python
Python 32-Bit Memory Limits on 64Bit Windows
Module' Object Has No Attribute 'Loads' While Parsing JSON Using Python