用于检查非法变量名称或关键字Python的网站

时间:2015-09-25 09:13:15

标签: python variables

我可能偶然发现了非法的变量名称

pass = "Pass the monkey!"
print pass

语法错误:语法无效

我知道有些关键词是作为变量而禁止的。 Pythonic是否等同于JavaScript variable name validator

3 个答案:

答案 0 :(得分:8)

您可以使用keyword模块

来测试某些内容是否为关键字
account id

https://docs.python.org/2/library/keyword.html

  

此模块允许Python程序确定字符串是否为a   关键字。

     

<强> keyword.iskeyword(S)

     

如果s是Python关键字,则返回true。

答案 1 :(得分:3)

某些变量名称在Python中是非法的,因为它是保留字。

来自Python文档中的keywords section

  

以下标识符用作保留字或关键字   语言,不能用作普通标识符。他们   必须完全按照这里所写的拼写:

# 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  

因此,您不能将上述任何标识符用作变量名。

答案 2 :(得分:2)

此函数将检查名称是Python中的关键字还是Python内置对象之一,可以是functionconstant,{{3}或type类。

import keyword
def is_keyword_or_builtin(name):
    return keyword.iskeyword(name) or name in dir(__builtins__)

虽然您无法使用Python keywords作为变量名称,但您可以使用Python built-ins进行此操作,但这被视为不良做法,因此我建议您避免使用它。