Last active
July 13, 2018 08:33
-
-
Save Proteusiq/820641eb6c527c3cd85d8536199c5739 to your computer and use it in GitHub Desktop.
get_imports.py
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 get_imports(): | |
import types | |
''' | |
returns a generator of packages and version numbers used in the script | |
use. print(set(get_imports())) to show the packages. packages that are | |
import directly e.g. from nltk.stem import SnowballStemmer won't be found | |
''' | |
for name, val in globals().items(): | |
if isinstance(val, types.ModuleType): | |
if hasattr(val, '__version__'): | |
yield val.__name__, val.__version__ | |
# package imported with "from x import y", and y.z we would like to get | |
# get x and x version if exits: WARNING Terrible coding below :( | |
# if you know better way, do let me know :) | |
if '.' in val.__name__: | |
try: | |
yield ( | |
val.__name__.split('.')[0], | |
eval("__import__('{}').__version__".format(val.__name__.split('.')[0]))) | |
except AttributeError: | |
# if package has no __version__ pass | |
pass | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment