Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #108441 > unrolled thread

Are imports supposed to be like this?

Started byBrendan Abel <007brendan@gmail.com>
First post2016-05-09 16:54 -0700
Last post2016-05-09 16:54 -0700
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Are imports supposed to be like this? Brendan Abel <007brendan@gmail.com> - 2016-05-09 16:54 -0700

#108441 — Are imports supposed to be like this?

FromBrendan Abel <007brendan@gmail.com>
Date2016-05-09 16:54 -0700
SubjectAre imports supposed to be like this?
Message-ID<mailman.552.1462838834.32212.python-list@python.org>
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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web