I've been reading a lot of threads, the PEP articles related to this problem, which are around 4 of them, but none of them gives a clear idea on some points and I still can't do relative imports.
In fact, the contents of my main package is not listed at all.
REEDITION. I modified all the post, it was too complex and questions were a lot.
In C:/test/ I have this package:
Package/ (FOLDER 2)
__init__.py
moduleA.py
moduleB.py
moduleAimportsmoduleB, and viceversa.__init__.pyis empty
My process:
- I add
C:/test/tosys.path. import Package(WORKS)dir(Package)Doesn't list any module inside Package.- Package is:
<module ‘Package’ from C:/test/Package/_init_.py> __file__is the init file under Package__name__isPackage__package__is an empty string__path__isC:/test/Package
TEST 1 - Version 1:
in moduleA I have from Package import moduleB
I get this:
>>> import Package.moduleA
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:/test\Package\moduleA.py", line
from Package import moduleB
File "C:/test\Package\moduleB.py", line
from Package import moduleA
ImportError: cannot import name moduleA
It doesn't work because moduleA is not part of Package. So Package is not recognized as a package?
TEST 1 - Version 2:
in moduleA I have from . import moduleB
Doesn't work, same error
TEST 1 - Version 3:
in moduleA I have import Package.moduleB
It works.
After that, running:
>>> dir(Package.moduleB)
['Package', '__builtins__', '__doc__', '__file__', '__name__', '__package__']
>>> Package.moduleB.Package
<module 'Package' from 'C:/prueba\Package\__init__.py'>
>>> dir(Package)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'moduleA', 'moduleB']
So now, Package.moduleB has Package as a variable
And surprisingly, Package how looks like a proper package, and contains both modules.
In fact, doing any of imports in Version 1 and Version 2 work now, because now moduleA and moduleB are part of Package.
Questions:
1) Why is Package not recognized as a package? Is it? Shouldn't it contain all submodules?
2) Why running import Package.moduleA generates Package inside moduleA?
3) Why running import Package.moduleA adds moduleA to Package and it wasn't there before?
4) Does an empty __init__.py file, and a NON empty __init__.py file affect to this at all?
5) Does defining an __all__ variable containing ['moduleA', 'moduleB'] would do anything here?
6) How can I make the init file to load both submodules? Should I do import Package.moduleA and Package.moduleB inside?... can't I do it relatively like import .moduleA as moduleA or something like that? (What If the name of Package changes?)
7) Does that empty string on the package variable affect? We should change it's contents if we want it to recognize itself... __package__ should be the same as __name__, or that's what the PEPs say. But doing this didn't work:
if __name__ == "__main__" and __package__ is None:
__package__ = "Package"