This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author antoine.pietri
Recipients antoine.pietri
Date 2013-06-05.19:17:53
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1370459873.38.0.323655253605.issue18145@psf.upfronthosting.co.za>
In-reply-to
Content
I just found a very strange bug today, and it took me like two hours to figure out the problem.

We first create a package "package", which contains an __init__.py, which makes an absolute import of package/foo.py (import package.foo), which makes an absolute import of package/bar.py (import package.bar).
Everything works fine as expected, the modules are imported correctly in the __init__.py and we can use them.

Now, if we move everything in a subpackage, the behavior is complete nonsense. We then have package/subpackage/{foo,bar,__init__}.py and an empty package/__init__.py.
We can import package.subpackage.foo and use it, but when we import package.subpackage.bar, the "import" statement works as expected but we CAN'T use the imported package:

>>> import package.subpackage.bar  # works fine
>>> dir(package.subpackage.bar)  # WAT
AttributeError: 'module' object has no attribute 'subpackage'

You can find a tarball attached to this bug report that contains the working case and the failing case:

package1
├── bar.py
├── foo.py
└── __init__.py

package2
└── subpackage
    ├── bar.py
    ├── foo.py
    └── __init__.py

$ python3
>>> import package1.foo
__init__: importing package1.foo
    foo.py: importing package1.bar
    foo.py: package1.bar.__name__: package1.bar
__init__: package1.foo.__name__: package1.foo
>>> import package2.subpackage.foo
__init__: importing package2.subpackage.foo
    foo.py: importing package2.subpackage.bar
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "./package2/subpackage/__init__.py", line 2, in <module>
    import package2.subpackage.foo
  File "./package2/subpackage/foo.py", line 3, in <module>
    print('    foo.py: package2.subpackage.bar.__name__:', package2.subpackage.bar.__name__)
AttributeError: 'module' object has no attribute 'subpackage'


tl;dr: you can use only relative imports to refer to modules of a package inside a module imported by the __init__.py of this package  except if the package is not a subpackage. Else, the package will be successfully imported but trying to use it will lead to a weird AttributeError. (Wat.)
History
Date User Action Args
2013-06-05 19:17:53antoine.pietrisetrecipients: + antoine.pietri
2013-06-05 19:17:53antoine.pietrisetmessageid: <1370459873.38.0.323655253605.issue18145@psf.upfronthosting.co.za>
2013-06-05 19:17:53antoine.pietrilinkissue18145 messages
2013-06-05 19:17:53antoine.pietricreate