Tianyun Ling
Tianyun Ling

Reputation: 1097

Python can't find nested package - ModuleNotFoundError

I have a project structure like:

enter image description here

My c.py is like:

def test():
    print('sub_package')

My b.py is like:

def test():

    import sub_package.c

    print(sub_package.c.test())

    print('test')

#test()

I can directly run b.py and get the imported sub_package with no problem.

But if I run main.py, which is like:

import package.b

print(package.b.test())

Python would complain:

Traceback (most recent call last):
  File "D:\test_package\main.py", line 1, in <module>
    import package.b
  File "D:\test_package\package\b.py", line 10, in <module>
    test()
  File "D:\test_package\package\b.py", line 4, in test
    import sub_package.c
ModuleNotFoundError: No module named 'sub_package'

It found package, but why the nested sub_package can't be found?

Upvotes: 1

Views: 86

Answers (1)

Kyle Willmon
Kyle Willmon

Reputation: 719

Python no longer supports implicit relative imports since the adoption of PEP-328

In this case, you would need to use an explicit relative import in b.py like so:

from .sub_package import c

print(c.test())

Or you can use an absolute import instead like so:

from package.sub_package import c

print(c.test())

Upvotes: 1

Related Questions