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

Viewed 9885

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:

  • I tried everything under OSX and Ubuntu Linux to reduce the possibility of a faulty python installation.
  • I set the PYTHONPATH environment variable to the myproject directory as well as to . and to both.
  • I left __init.py__ blank
  • I tried the import statements also from the python interpreter started from the myproject directory
  • I tried the following import statements:

    from MyPackage import mymodule
    import MyPackage.mymodule
    import MyPackage.mymodule as module
    

    all without success (same error message).

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!

1 Answers
Related