John Prawyn
John Prawyn

Reputation: 1663

Struggling to understand python package and import statment

I have a package like this

sound/
    __init__.py
   effects/
       __init__.py
       echo.py
   formats/
      __init__.py
     avi.py

inside avi.py i have import statement like this

from sound.effects import echo

this code throws No Module Named sound.effect error

From the pythondocs i understood that this is possible. And I am search through stackoverflow and found related question and answers, but I couldn't understand them.

Please help me to solve this.

Thanks,

Prawyn.

Upvotes: 1

Views: 164

Answers (3)

Demian Brecht
Demian Brecht

Reputation: 21368

I'm going to assume that sound.effect is a typo and is sound.effects. If that's the case, then the issue is likely due to your project structure.

If the root level of your project is sound as in your diagram and you've added it to your PYTHONPATH (or any number of other installation methods), then Python won't know where to look for sound (as there's no directory relative to your root directory named sound).

So, generally you'll see package structures such as:

sound/
    README
    LICENSE
    setup.py
    sound/
        __init__.py

...And so on.

With your current directory structure (and if my assumption is correct), then the import that will actually work is from effects import echo.

Upvotes: 1

m01
m01

Reputation: 9385

If you're running avi.py from the formats folder, and don't adjust your PYTHONPATH, Python won't be able to find the effects package. Try running your code from outside the sounds directory, modifying your PYTHONPATH environment variable such that it includes the directory in which sound lives is part of thtat, or changing your PYTHONPATH at runtime (see e.g. this link).

Upvotes: 2

Amber
Amber

Reputation: 526633

If the folder name is effects, why are you trying to import from effect? Try from sound.effects import echo instead.

Also, why are you trying to import echo from within itself?

Upvotes: 2

Related Questions