Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is __init__.py required for every python package? [new feature since python 3.3+]

I have see this in python tutorial:

The __init__.py files are required to make Python treat the directories as containing packages;

I make the directory hierarchy in pycharm like this, where the subdir1 doesn't contain __init__.py and subdir2 contains a __init__.py file. enter image description here

First, I add Directory into system.pyth.

I write a hello function in hello1.py and hello2.py respectively.

Then I call hello func in test files like this:

# test1.py
from subdir1 import hello1
hello1.hello()

# test2.py
from subdir2 import hello2
hello2.hello()

They all succeed. It seems that the __init__.py does not necessary for import modules from different directories, right?

So, I want to know in what situation a __init__.py is required. Thanks for your answering!

like image 761
Bicheng Avatar asked Jul 25 '26 07:07

Bicheng


1 Answers

Python 3.3+ has implicit namespace packages that allow you to create packages without __init__.py. In Python 2, __init__.py is the old method and still works.

Allowing implicit namespace packages means that the requirement to provide an __init__.py file can be dropped completely, and affected portions can be installed into a common directory or split across multiple directories as distributions see fit.

Note: init.py files were used to mark directories on your disk as Python packages.

Useful links:

  1. Implicit Namespace Packages
like image 88
mrhallak Avatar answered Jul 26 '26 22:07

mrhallak