A Python module and package loading confusion

2020-02-06 13:40发布

问题:

Let's say I have something like this:

.
├── run.py
└── test
    ├── __init__.py
    ├── models
    │   ├── foo
    │   │   ├── baby.py
    │   │   └── __init__.py
    │   ├── __init__.py
    │   └── user.py
    └── start.py

run.py

from test import start

start.py

from .models import user

user.py

from . import foo

print(foo.baby.Baby)

baby.py

Baby = "I am a baby"

Now, when you run the run.py file...

>>> python run.py
... traceback ...
AttributeError: 'module' object has no attribute 'baby'

But, if you change the start.py like this:

from .models.foo import baby
from .models import user

everything works correctly.

When the baby module in start.py wasn't loaded earlier, the foo package object did not have a reference to it (foo.baby.Baby threw an AttributeError). But when I loaded the baby module in start.py, the foo package object automatically got a reference to babymodule.

Can someone explain me how this works?

回答1:

Submodules are not automatically attributes of a package until imported.

You need to import test.models.foo.baby first before foo.baby.Baby works. You can do this in the foo/__init__.py file:

from . import baby