Created
September 17, 2014 21:25
-
-
Save carymrobbins/16c5c520d0d2a048ab59 to your computer and use it in GitHub Desktop.
Parse version number from python source. Really, this could be more generalized to parse any variables (given obvious restrictions) from source.
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
| import ast | |
| def parse_version(source, name='__version__'): | |
| for exp in ast.parse(source).body: | |
| if isinstance(exp, ast.Assign) and name in (t.id for t in exp.targets): | |
| if len(exp.targets) != 1: | |
| raise ValueError('Cannot parse assignment unpacking.') | |
| if isinstance(exp.value, ast.Str): | |
| return exp.value.s | |
| if isinstance(exp.value, (ast.Tuple, ast.List)): | |
| return '.'.join(map(str, ast.literal_eval(exp.value))) | |
| raise TypeError('Invalid version type "{0}", must be Str, Tuple, or List.' | |
| .format(type(exp.value).__name__)) | |
| raise ValueError('Name "{0}" not found in source.'.format(name)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment