Created
August 26, 2018 08:50
-
-
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.
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
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