import os import sys from pathlib import Path class LayeredObject: def __init__(self, *objects): self._objects = objects def __getattr__(self, item): for o in self.__dict__['_objects']: try: if isinstance(o, dict): return o[item] elif isinstance(o, os._Environ): return o[item.upper()] else: return getattr(o, item) except (AttributeError, KeyError): pass raise AttributeError(f"None of the objects contained in '{self.__class__.__name__}' have attribute '{item}'.\n" f"Objects contained: {[repr(o) for o in self.__dict__['_objects']]}") def import_module(path): path = Path(path) assert path.suffix == '.py', f'expected a path to a python module, got {path}' sys.path.insert(1, str(path.parent)) mod = __import__(path.stem) sys.path.remove(str(path.parent)) return mod