Created
September 5, 2016 13:44
-
-
Save dmmfll/bfc4ecb1b467eaf88b7e493acf81f2d9 to your computer and use it in GitHub Desktop.
valid Python identifier tester using ast
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""http://stackoverflow.com/questions/12700893/how-to-check-if-a-string-is-a-valid-python-identifier-including-keyword-check""" | |
import ast | |
def isidentifier(ident): | |
"""Determines, if string is valid Python identifier.""" | |
# Smoke test — if it's not string, then it's not identifier, but we don't | |
# want to just silence exception. It's better to fail fast. | |
if not isinstance(ident, str): | |
raise TypeError('expected str, but got {!r}'.format(type(ident))) | |
# Resulting AST of simple identifier is <Module [<Expr <Name "foo">>]> | |
try: | |
root = ast.parse(ident) | |
except SyntaxError: | |
return False | |
if not isinstance(root, ast.Module): | |
return False | |
if len(root.body) != 1: | |
return False | |
if not isinstance(root.body[0], ast.Expr): | |
return False | |
if not isinstance(root.body[0].value, ast.Name): | |
return False | |
if root.body[0].value.id != ident: | |
return False | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment