Sede
Sede

Reputation: 61293

NameError when automatically loading a submodules

I have package structure like this:

sound/
├── effects
│   ├── echo.py
│   ├── __init__.py
│   └── reverse.py
├── formats
│   ├── __init__.py
│   ├── waveread.py
│   └── wavewrite.py
└── __init__.py

Then to automatically load the submodule echo and reverse I added the following import statement into my effects/__init__.py file

from . import echo
from . import reverse

However after I imported sound.effects I still have a NameError when trying to access echo and reverse:

>>> import sound.effects
>>> echo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'echo' is not defined
>>> reverse
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'reverse' is not defined

Am I missing something?

Upvotes: 1

Views: 140

Answers (2)

ig0774
ig0774

Reputation: 41287

Basically this is how Python namespacing works.

Adding:

from . import echo

To effect/__init__.py imports the name echo into the effect namespace. When you import a module it executes the module code but in the module namespace not your main programs namespace.

In your example, you could access echo as sound.effect.echo or even import it (in your main file) as:

from sound.effect import echo

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 600059

Yes. You imported sound.effects, but that doesn't bring the contents of effects into your current namespace. You still need to refer to them where they are: sound.effects.echo and sound.effects.reverse.

If you want to just refer to them by name, you need to import those names:

from sound.effects import echo, reverse

Upvotes: 3

Related Questions