Last active
August 29, 2015 14:11
-
-
Save stnbu/4d29b89a8f0aebb17180 to your computer and use it in GitHub Desktop.
Test to see if "name" is a 'valid' python identifier: does it have spaces? begin with a numeral, etc, etc. Pretty crude.
This file contains 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
def is_valid_identifier(name): | |
"""Pedantic yet imperfect. Test to see if "name" is a valid python identifier | |
""" | |
if not isinstance(name, basestring): | |
return False | |
if set('\n\t\r') & set(name): | |
return False | |
if name.strip() != name: | |
return False | |
try: | |
code = compile('\n{0}=None'.format(name), filename='<string>', mode='single') | |
exec(code) | |
return True | |
except SyntaxError: | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment