Are imports supposed to be like this?

Brendan Abel 007brendan at gmail.com
Mon May 9 19:54:00 EDT 2016


Consider the following example python package where `a.py` and `b.py`
depend on each other:

    /package
        __init__.py
        a.py
        b.py


There are several ways I could import the "a.py" module in "b.py"

    import package.a           # Absolute import
    import package.a as a_mod  # Absolute import bound to different name
    from package import a      # Alternate absolute import
    import a                   # Implicit relative import (deprecated, py2
only)
    from . import a            # Explicit relative import

Unfortunately, only the 1st and 4th syntax actually work when you have
circular dependencies (the rest all raise `ImportError` or
`AttributeError`), and the 4th syntax only works in python 2 and is
generally discouraged because of the possibility of name conflicts.

I'd much rather use relative imports, or the "from x import y" syntax, or
at least be able to use the "as" import syntax.  If I have a deeply nested
package, the imports become unruly rather quickly, and I have to use that
long, ugly name throughout the entire module!

    import package.subpackage.submodule.module  # fugly!

Are imports designed to work this way, or is this a bug in the import
machinery?  What reasoning is there for the first syntax to work, but all
the others should fail?  Admittedly, I haven't used Python3 yet, does it
fix this?  It seems odd to me that the documentation seems to encourage
relative imports or at least the "from x.y.z import a" forms of imports,
yet they don't work the same as "import x.y.z.a".


//Brendan



More information about the Python-list mailing list