I may have stumbled on an illegal variable name
pass = "Pass the monkey!"
print pass
Syntax error: invalid syntax
I'm aware that some keywords are verboten as variables. Is there the Pythonic equivalent to JavaScript variable name validator?
I may have stumbled on an illegal variable name
pass = "Pass the monkey!"
print pass
Syntax error: invalid syntax
I'm aware that some keywords are verboten as variables. Is there the Pythonic equivalent to JavaScript variable name validator?
You can test whether something is a keyword or not using the keyword module
>>> import keyword
>>> keyword.iskeyword("pass")
True
>>> keyword.iskeyword("not_pass")
False
https://docs.python.org/2/library/keyword.html
This module allows a Python program to determine if a string is a keyword.
keyword.iskeyword(s)
Return true if s is a Python keyword.
Some variable names are illegal in Python because of it being a reserved word.
From the keywords
section in the Python docs:
The following identifiers are used as reserved words, or keywords of the language, and cannot be used as ordinary identifiers. They must be spelled exactly as written here:
# Complete list of reserved words
and
del
from
not
while
as
elif
global
or
with
assert
else
if
pass
yield
break
except
import
print
class
exec
in
raise
continue
finally
is
return
def
for
lambda
try
True # Python 3 onwards
False # Python 3 onwards
None # Python 3 onwards
nonlocal # Python 3 onwards
async # in Python 3.7
await # in Python 3.7
So, you cannot use any of the above identifiers as a variable name.
This function will check if a name is a keyword in Python
or one of Python built-in objects, which can be a function, a constant, a type or an exception class.
import keyword
def is_keyword_or_builtin(name):
return keyword.iskeyword(name) or name in dir(__builtins__)
While you can't use Python keywords
as variable names, you are allowed to do it with Python built-ins
though it's considered a bad practice so I will recommend to avoid it.