pythonnamespace-package

Does importing a namespace package also import the modules in the directory?


This explanation of package imports says that importing a package packB without an __init__.py file doesn't do anything because __init__.py tells the import process what other *.py files to import.

I'm at a loss as to how that is useful. I'm a Python newbie, but everything I've read online says that such an "implicit namespace package" lacks __init__.py files because there may be multiple packB folders whose contents are to be combined into a common packB namespace.

Is this simply an error in the page cited above, or is there a clearer explanation that I just haven't found?


Solution

  • Packages may have optional modules that are only imported as needed. It would be bad form for python to automatically import everything in a package, just in case.

    Originally packages where required to have an __init__.py and that module was imported as the package namespace. This was deemed important so that a parent directory in sys.path could also hold non-python subdirectories without confusion. The __init__.py gave the package writer a place to import any modules it deemed necessary at package import.

    But the desire to split a package into multiple deliverables made that requirement more difficult - which of these deliverables would hold the required __init__.py. Eventually, this second usage won out.

    Now, if you have a directory with .py files in it, but no __init__.py, python will import it as an empty namespace. It's not useless, because it still gives a parent namespace for the other modules in the package, even if they need their own import.

    If I have

    foo/
        time.py
    

    the empty "foo" still differentiates my optionally-imported foo.time module from the standard library time module. import foo may only be marginally useful, but import foo.time is not. import foo has the marginal advantage of testing that the foo is installed on this system without any assumptions about which deliverables have been installed.