In this situation, Python 3 does not need __init__.py?

Suppose I have:

src/ __init__.py a.py b.py 

Suppose __init__.py is an empty file, and a.py is just one line:

 TESTVALUE = 5 

Assume b.py :

 from src import a print(a.TESTVALUE) 

Now, in both Python 2.7 and Python 3.x, running b.py gives the result ( 5 ).

However, if I delete the __init__.py file, b.py still works in Python 3.x, but in Python 2.7 I get an error:

 Traceback (most recent call last): File "b.py", line 5, in <module> from src import a ImportError: No module named src 

Why is Python 2.7 exhibiting different behavior in this situation?

+5
source share
1 answer

Python 3 supports namespace packages that work without the __init__.py file. In addition, these packages can be distributed across several directories. This means that all directories on your sys.path that contain *.py files will be recognized as packages.

This reduces backward compatibility in Python 3 in terms of imports. A typical problem is the directory in your current working directory, which has a name similar to a library, such as numpy and contains Python files. Although Python 2 ignores this directory, Python 3 will find it first and try to import the library from there. It has bitten me several times.

+8
source

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


All Articles