Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Import This, That, and the Other Thing

Brett Cannon
February 12, 2010

Import This, That, and the Other Thing

PyCon 2010

Brett Cannon

February 12, 2010
Tweet

More Decks by Brett Cannon

Other Decks in Programming

Transcript

  1. for entry in search: finder = sys.path_importer_cache [entry] loader =

    finder.find_module(name) return loader.load_module(name) Search path hook False True False finder raise ImportError True
  2. for hook in sys.path_hooks: finder = hook(entry) sys.path_importer_cache[entry] = finder

    sys.path_importer_cache[entry] = dummy path hook finder False True
  3. Option 3: importers http://packages.python.org/importers/ File path abstraction on top of

    importlib. Treating as purgatory for importlib inclusion.
  4. Tell the loader if package & path to code Don’t

    Repeat Yourself ... within reason.
  5. Reasons to ignore .pyc • Jython, IronPython couldn’t care less.

    • Safe to support, though. • Another thing to code up. • Bytecode is just an optimization. • If you only ship .pyc for code protection, stop it.
  6. class Module(types.ModuleType): pass class Mixin: def load_module(self, name): if name

    in sys.modules: return super().load_module(name) # Create a lazy module that will type check. module = LazyModule(name) # Set the loader on the module as ModuleType will not. module.__loader__ = self # Insert the module into sys.modules. sys.modules[name] = module return module class LazyModule(types.ModuleType): def __getattribute__(self, attr): # Remove this __getattribute__ method by re-assigning. self.__class__ = Module # Fetch the real loader. self.__loader__ = super(Mixin, self.__loader__) # Actually load the module. self.__loader__.load_module(self.__name__) # Return the requested attribute. return getattr(self, attr)
  7. Fin