5

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?

Mr Mystery Guest
  • 1,464
  • 1
  • 18
  • 47
  • 2
    Related http://stackoverflow.com/q/29346945/4099593 – Bhargav Rao Sep 25 '15 at 09:16
  • There are so many related questions: http://stackoverflow.com/questions/22864221/is-the-list-of-python-reserved-words-and-builtins-available-in-a-library; http://stackoverflow.com/questions/14595922/list-of-python-keywords; http://stackoverflow.com/questions/9642087/is-it-possible-to-get-a-list-of-keywords-in-python – cezar Sep 25 '15 at 09:17
  • 1
    Python's compiler _is_ your "variable name validator" - as you just found out. Note that Python doesn't have that many keywords and that any half-decent code editor should identify and hilight them properly. – bruno desthuilliers Sep 25 '15 at 10:07

3 Answers3

11

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.

Joe Young
  • 5,749
  • 3
  • 28
  • 27
5

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.

Rahul Gupta
  • 46,769
  • 10
  • 112
  • 126
3

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.

Forge
  • 6,538
  • 6
  • 44
  • 64