Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 doesn't need __init__.py in this situation?

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

Suppose b.py is:

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 file __init__.py, b.py still works in Python 3.x, but in Python 2.7, I get the error:

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

Why does Python 2.7 exhibit different behaviour in this situation?

like image 984
Michael Currie Avatar asked Jan 23 '16 22:01

Michael Currie


1 Answers

Python 3 supports namespace packages that work without an __init__.py file. Furthermore, these packages can be distribute over several directories. This means all directories on your sys.path that contain *.py files will be recognized as packages.

This breaks backwards compatibility in Python 3 in terms of imports. A typical problem is a directory in your current working directory that has a name like a library such as numpy and that contains Python files. While Python 2 ignores this directory, Python 3 will find it first and tries to import the library from there. This has bitten me several times.

like image 55
Mike Müller Avatar answered Sep 21 '22 08:09

Mike Müller