2

I failed to import a module from sub directory in python. Below is my project structure.

./main.py
./sub
./sub/__init__.py
./sub/aname.py

when I run python main.py, I got this error:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    import sub.aname
  File "/Users/dev/python/demo/sub/__init__.py", line 1, in <module>
    from aname import print_func
ModuleNotFoundError: No module named 'aname'

I don't know it failed to load the module aname. Below is the source code:

main.py:

#!/usr/bin/python

import sub.aname

print_func('zz')

sub/__init__.py:

from aname import print_func

sub/aname.py:

def print_func( par ):
   print ("Hello : ", par)
   return

I am using python 3.6.0 on MacOS

MSeifert
  • 145,886
  • 38
  • 333
  • 352
Joey Yi Zhao
  • 37,514
  • 71
  • 268
  • 523

3 Answers3

0
from sub import aname
aname.print_func('zz')
Benjamin Toueg
  • 10,511
  • 7
  • 48
  • 79
0

Probably the most elegant solution is to use relative imports in your submodule sub:

sub.__init__.py

from .aname import print_func

But you also need to import the print_func in main.py otherwise you'll get a NameError when you try to execute print_func:

main.py

from sub import print_func   # or: from sub.aname import print_func

print_func('zz')
MSeifert
  • 145,886
  • 38
  • 333
  • 352
0

There are several mistakes in your Python scripts.

Relative import

First, to do relative import, you must use a leading dots (see Guido's Decision about Relative Imports syntax).

In sub/__init__.py, replace:

from aname import print_func

with:

from .aname import print_func

Importing a function

To import a function from a given module you can use the from ... import ... statement.

In main.py, replace:

import sub.aname

with:

from sub import print_func
Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103