3

My filesystem structure:

  • main.py.
  • lib/
    • __init__.py.
    • subpackage/
      • __init__.py.
      • app.py
      • sched.py

main.py:

import lib.subpackage

lib/__init__.py is empty.

lib/subpackage/__init__.py:

import lib.subpackage.sched
import lib.subpackage.app

lib/subpackage/app.py:

import lib.subpackage.sched as foo

lib/subpackage/sched.py is empty.


I'm getting this error:

Traceback (most recent call last):
  File "c:\Users\logix\Desktop\code_\from_linux\dbg\main.py", line 1, in <module>
    import lib.subpackage
  File "c:\Users\logix\Desktop\code_\from_linux\dbg\lib\subpackage\__init__.py", line 2, in <module>
    import lib.subpackage.app
  File "c:\Users\logix\Desktop\code_\from_linux\dbg\lib\subpackage\app.py", line 1, in <module>
    import lib.subpackage.sched as foo
AttributeError: module 'lib' has no attribute 'subpackage'

I'm using Python 3.6.4 from the command line.

Any ideas?

Stefan Monov
  • 11,332
  • 10
  • 63
  • 120

1 Answers1

2

This is a known bug in the import machinery, when using an alias; reported as issue #23203:

Aliasing import of sub-{module,package} from the package raises AttributeError on import.

We have three nested packages: foo -> bar -> baz. The bar package imports foo.bar.baz. We try to import foo.bar. This works well unless we try to alias the foo.bar.baz import in foo.bar with the import ... as ... syntax.

The bugfix for this is part of Python 3.7 (currently in alpha release only).

The work-around is to use a relative import:

from . import sched as foo
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343