2015-09-25 29 views
1

我可能無意中發現了一個非法的變量名網站檢查非法變量名或關鍵字的Python

pass = "Pass the monkey!" 
print pass 

語法錯誤:無效的語法

我知道,一些關鍵字禁止的作爲變量。 是否有相當於JavaScript variable name validator的Pythonic?

+2

相關http://stackoverflow.com/q/29346945/4099593 –

+0

有這麼多相關的問題:http://stackoverflow.com/questions/22864221/is-the-list-of-python-reserved-words -and-內建可用-IN-A-庫; 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

+1

Python的編譯器_is_你的「變量名稱驗證器」 - 就像你剛剛發現的那樣。請注意,Python沒有那麼多的關鍵字,並且任何一個不太合適的代碼編輯器都應該正確地識別它們並使它們高亮。 –

回答

8

您可以測試一些是否是關鍵字或不使用keyword模塊

>>> 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

你也可以檢查內建的名字:'dir(__ builtins __)' –

3

一些變量名是非法在Python,因爲它是一個保留字。

從Python文檔的keywords section

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 

所以,你不能使用任何上述標識符作爲變量名。

+1

來一個新的python 3. 7在你附近還有兩個:['async'和'await'](https:// www .python.org的/ dev/PEPS/PEP-0492 /)。 – NightShadeQueen

+1

@NightShadeQueen:他們將成爲Python 3.7中的正確關鍵字。 –

+0

@NightShadeQueen感謝您的信息。更新了ans。 –

2

此功能將檢查是否一個名字是在Python或內置對象的Python一個關鍵字,它可以是一個function,一個constant,一個typeexception類。

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

雖然你不能使用Python keywords作爲變量名,你被允許雖然它被認爲是一種不好的做法,所以我會建議,以避免它與Python built-ins做到這一點。

+1

我會添加一個註釋,說明內建的名稱不是非法的變量名稱,雖然他們的使用不鼓勵(由於顯而易見的原因)。 –

+0

這很好,謝謝@AndreaCorbellini。 – Forge

+0

這是一個python 3.x的東西嗎? print keyword.iskeyword.iskeyword(pass)不起作用「關鍵字」未定義。 –

相關問題