Consider the following hierarchy of three regular packages and their contents:
quick
├── brown
│ ├── fox.py
│ └── __init__.py
├── lazy
│ ├── dog.py
│ └── __init__.py
└── __init__.py
Now suppose there is a function jump
in module dog
and it is needed in module fox
. How should I proceed?
Having recently seen Raymond Hettinger's talk at Pycon
2015 I would the like
the function to be directly importable from the root of package lazy
,
like this:
from lazy import jump
Also, it seems to me that writing relative imports is more concise and
makes the intra-package connections easily visible. Hence, I'd write
this into lazy/__init__.py
:
from .dog import jump
And this into fox.py
:
from ..lazy import jump
But I wonder, is this the right way?
First, importing the name jump
in lazy/__init__.py
does nothing to
prevent it from being imported directly from dog
. Can it cause problems if a function is potentially imported from many places? For instance, in unit testing, can we possibly monkey patch the name from a wrong location?
Moreover, IDEs with their auto-import routines seem to prefer importing from the module where the function is defined. I could perhaps override this by putting character _
in front of all module names, but this seems a bit impractical.
Is it otherwise dangerous to bring all names that are needed outside a
package to __init__.py
? Probably this at least increases the
possibility of circular imports. But I guess that if a circular
import is encountered there is something fundamentally wrong with the
package structure anyway.
What about the relative imports? PEP 8 says that absolute imports are recommended: what does it mean when it says that absolute imports behave better than the relative ones? Can you give me an example?