[issue21235] importlib's spec module create algorithm is not exposed

Brett Cannon report at bugs.python.org
Mon May 26 16:49:25 CEST 2014


Brett Cannon added the comment:

I think that's the wrong abstraction(it would be fine in a third-party library, though, that's trying to smooth over 3.3->3.4 transitions). Since importlib.util.find_spec() always returns a spec, then you want something more like::

  def load(spec):
    loader = spec.loader
    if hasattr(loader, 'exec_module'):
        module = importlib.util.whatever_issue_20383_leads_to()
        loader.exec_module(module)
        return module
    else:
        loader.load_module(spec.name)
        return sys.modules[spec.name]

Since this is Python 3.5 code we are talking about you don't have to worry about the find_loader/find_module case as find_spec wraps both of those and normalizes it all to just using specs. You could even tweak it to pass the module in explicitly and in the load_module branch make sure that the module is placed in sys.modules first so it essentially becomes a reload (but as both know that's not exactly the same nor pleasant in certain cases so probably best not exposed that way =).

If this exists in importlib.util then you make import_module() be (essentially)::

  def import_module(name, package):
    fullname = resolve_name(name, package)
    spec = find_spec(fullname)
    return load(spec)

----------
dependencies: +Add a keyword-only spec argument to types.ModuleType

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue21235>
_______________________________________


More information about the Python-bugs-list mailing list