Python module search path

I have a project like this:

foo/
| main.py
| bar/
| | module1.py
| | module2.py
| | __init__.py

with main.pydoing import bar.module1and module1.pydoing import module2.

This works using python 2.6, but not python 3.1 ( ImportError: No module named module2)

Why has the behavior changed? How to restore it?

+3
source share
1 answer

In module1.py, execute a: from . import module2

main.py

import bar.module1
print(bar.module1.module2.thing)

bar / INIT .py

#

Bar / module 1.py

#import module2 # fails in python31
from . import module2 # intrapackage reference, works in python26 and python31

Bar / module 2.py

thing = "blah"

How and why / how, which is higher than my paygrade. The documentation does not seem to clarify it. Maybe in Python 3 they decided to force the use of submodules in packages explicitly imported using the intrapackage style?

+6

Source: https://habr.com/ru/post/1760584/


All Articles