Instead of wondering whether a variable name is a reserved keyword, use Python's keyword
library to find out!
>>> import keywords
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
(Side note: I'm surprised that the data structure returned in the code snippet above is an ordered list. Why not use a set? Is it because the word list
is used in the name kwlist
?)
If you prefer, there's a keyword.iskeyword()
function that takes in a string and returns a boolean.
I found this library while looking for a way to determine whether a variable shares its name with an imported library or already-defined function, a problem that I haven't quite yet solved. I'm aware that functions like callable()
let you know if a variable is a function (or rather, a callable), but I don't know how to check if a variable is also the name of an importable module.
For example, string
is a plausible generic variable name, but it's only good if the string
library isn't being imported too. And while I'm able to avoid using string
for my variable names because I'm already aware of the string
library, I can't possibly know all library names, especially when so many will be created custom for the code repository I'm working with. So what do I do for those cases?
Solve my mystery please.