Skip to content

Instantly share code, notes, and snippets.

@davidbau
Created August 26, 2018 08:50
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 davidbau/0da7695d2b5b58dded183b0d12342cf1 to your computer and use it in GitHub Desktop.
Save davidbau/0da7695d2b5b58dded183b0d12342cf1 to your computer and use it in GitHub Desktop.
Used to eval python expressions containing arbitrary fully-qualified package names, automatically importing packages as needed.
from collections import defaultdict
from importlib import import_module
def autoimport_eval(term):
'''
Used to eval any expression containing fully-qualified names, such as
'torchvision.models.alexnet(pretrained=True)' with automatic import of
global module names.
'''
class DictNamespace(object):
def __init__(self, d):
self.__d__ = d
def __getattr__(self, key):
return self.__d__[key]
class AutoImportDict(defaultdict):
def __init__(self, parent=None):
super().__init__()
self.parent = parent
def __missing__(self, key):
if self.parent is not None:
key = self.parent + '.' + key
if hasattr(__builtins__, key):
return getattr(__builtins__, key)
mdl = import_module(key)
# Return an AutoImportDict for any namespace packages
if hasattr(mdl, '__path__') and not hasattr(mdl, '__file__'):
return DictNamespace(AutoImportDict(key))
return mdl
return eval(term, {}, AutoImportDict())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment