Website to check Illegal variable names or keywords Python [duplicate]

风格不统一 提交于 2021-01-27 18:09:54

问题


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?


回答1:


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.




回答2:


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.




回答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.



来源:https://stackoverflow.com/questions/32778732/website-to-check-illegal-variable-names-or-keywords-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!