Skip to content

Instantly share code, notes, and snippets.

@Proteusiq
Last active July 13, 2018 08:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Proteusiq/820641eb6c527c3cd85d8536199c5739 to your computer and use it in GitHub Desktop.
Save Proteusiq/820641eb6c527c3cd85d8536199c5739 to your computer and use it in GitHub Desktop.
get_imports.py
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