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

The amazing disappearing import by Bruce Merry

Pycon ZA
October 11, 2018

The amazing disappearing import by Bruce Merry

A Lightning Talk at PyConZA 2018

Pycon ZA

October 11, 2018
Tweet

More Decks by Pycon ZA

Other Decks in Programming

Transcript

  1. Sometimes importing a package implicitly imports submodules: In [1]: import

    numpy numpy.lib And sometimes it doesn't: In [2]: import tornado tornado.gen Out[1]: <module 'numpy.lib' from '/home/bmerry/work/sdp/env3/lib/python3.5/site-packages/numpy/lib/__init__.py'> --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-2-ac9fe21bb8d4> in <module>() 1 import tornado ----> 2 tornado.gen AttributeError: module 'tornado' has no attribute 'gen'
  2. And sometimes... bizarre things happen: In [3]: import katdal.h5datav3 katdal.h5datav3

    --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-3-ea693ef56394> in <module>() 1 import katdal.h5datav3 ----> 2 katdal.h5datav3 AttributeError: module 'katdal' has no attribute 'h5datav3'
  3. What happens when you import What happens when you import

    It's surprisingly complicated. But in simple terms: import foo.bar will 1. Load module foo (call it foo_module) 2. Load module foo.bar (call it foobar_module) 3. Do foo_module.bar = foobar_module 4. Do your_module.foo = foo
  4. Corollaries Corollaries If module foo internally imports foo.bar, it will

    be available That's true even if it does from .bar import Baz
  5. The mystery solved The mystery solved In katdal/__init__.py : from

    .h5datav1 import H5DataV1 from .h5datav2 import H5DataV2 from .h5datav3 import H5DataV3 ... # Clean up top-level namespace a bit del h5datav1, h5datav2, h5datav3