mhelwig
mhelwig

Reputation: 121

Python cannot import module from subdirectory even with a file named __init.py__ in the directory

I know this question has been asked many times here and I'v probably read most of the answers (including this and that) as well as the python documentation but still can not find an answer to my very simple import problem. It's so simple that I must miss something stupid but I don't see it yet. I have setup the following structure:

myproject
    myscript.py
    MyPackage
        __init.py__
        mymodule.py

I just want to load mymodule.py from myscript.py (or the commandline python interpreter which should be the same).

myscript.py contains:

#!/usr/bin/python
import MyPackage

__init.py__ contains:

from . import mymodule

mymodule.py contains

#!/usr/bin/python

def myfunction():
    print "mymessage"

My goal is to call myfunction from myscript.py but if I try to call the module I get

$python myscript.py 
Traceback (most recent call last):
   File "myscript.py", line 2, in <module>
   import MyPackage
ImportError: No module named MyPackage

What I already tried:

If I put mymodule.py in the project directory without using a package, import works fine. But I don't see why the import from the subpackages is not working. Any idea how I can get that to work?

Thanks for help!

Upvotes: 12

Views: 11242

Answers (1)

Lukas Graf
Lukas Graf

Reputation: 32630

While editing the formatting of your post, I noticed you're calling your file __init.py_. That causes python to not recognize your MyPackage directory as a package, hence the ImportError: No module named MyPackage.

It should instead be __init__.py (Name __init__, extension .py). Then it will work, your project structure and import statements are otherwise correct.

One minor point though: You should also use lower_underscore style for naming your package. Packages are modules as well in Python, and they should follow the same naming conventions. See PEP8 for details on recommended style and naming conventions. This is just a convention though, it has nothing to do with your problem.

Upvotes: 8

Related Questions