I just noticed that relative import like this:
from .foo import myfunc
print myfunc # ok
print foo # ok
imports both foo and myfunc. Is such behaviour documented anywhere? Can I disable it?
— Update
Basically problem is following.
bar/foo/__init__.py:
__all__ = ['myfunc']
def myfunc(): pass
bar/__init__.py:
from .foo import *
# here I expect that there is only myfunc defined
main.py:
import foo
from bar import * # this import shadows original foo
I can add __all__ to the bar/__init__.py as well, but that way I have to repeat names in several places.
I am assuming your package layout is
The statement
from .foo import myfuncfirst imports the modulefoo, generally without introducing any names into the local scope. After this first step,myfuncis imported into the local namespace.In this particular case, however, the first step also imports the module into the local namespace: sub-modules of packages are put in the package’s namespace upon importing, regardless from where they are imported. Since
__init__.pyis also executed in the package’s namespace, this happens to conincide with the local namespace.You cannot reasonably disable this behaviour. If you don’t want the name
fooin your package’s namespace, my advice is to rename the module to_footo mark it as internal.