Skip to content

Instantly share code, notes, and snippets.

@stnbu
Last active August 29, 2015 14:11
Show Gist options
  • Save stnbu/4d29b89a8f0aebb17180 to your computer and use it in GitHub Desktop.
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.
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