What is __init__.py for?

February 27, 2024

What does __init__.py do?

1. Overview

You often see an __init__.py file in Python. It can look superfluous, especially when it is completely empty. What is it actually for?

In a Python project, think of a package as a directory and a module as a .py file. When you create a Python Package in PyCharm, the IDE automatically creates an __init__.py for you. It initializes the package. Let’s look at what that means in practice.

💡 Tip: Since Python 3.3, a namespace package can exist without an empty __init__.py. If you want to explicitly expose particular modules through the package, you can specify them in __init__.py.

2. What happens when Python loads the file?

A small example makes its role easier to see.

Here is the directory structure:

.
├── demo.py
├── package
|   ├── __init__.py
|   ├── module.py
# ./demo.py
import package

# ./pacakge/__init__.py
print("__init.py file is called!")

When I run demo.py, I get the following output:

$ python demo.py 
__init.py file is called!

The code in __init__.py ran. Changing import package in demo.py to import package.module produces the same result. When something is imported from a package, the package initialization runs first.

3. What can we use it for?

3.1 Simplifying imports

Suppose module.py defines a_function():

# ./pacakge/module.py
def a_function():
    print("Test function is called!")

Without an __init__.py exposing the function, I would call it from demo.py as follows (method one):

# ./demo.py
from package.module import a_function
a_function()

I can also put this definition in __init__.py:

# ./pacakge/__init__.py
from package.module import a_function

Then I can call it from demo.py like this (method two):

# ./demo.py
from package import a_function
a_function()

It may not look much shorter here. Imagine a package with dozens of modules and dozens or hundreds of functions. Method one could require dozens of import statements in demo.py. Method two lets me put the imports together in __init__.py. The next two points are even more significant.

3.2 Importing names in bulk, controlling exports, and __all__

What if you define many functions in module.py and want to use them in demo.py? Suppose module.py contains these two:

# ./pacakge/module.py
def a_function_1():
    print("Test function 1 is called!")
def a_function_2():
    print("Test function 2 is called!")
# 先在__init__.py批量导入
# ./pacakge/__init__.py
from package.module import *

# 再在demo.py中批量导入
# ./demo.py
from package import *
a_function_1()

You can now import many functions from the package at once. Be aware of name collisions: if classes or methods share a name, a later import overwrites the earlier binding. If you only want to expose a_function_1, you can change __init__.py to the following:

# 这样在demo.py文件中,调用a_function_2就会报错。

from package.module import a_function_1

# ./demo.py
from package import *
a_function_2()    # 这里就会报错

A more explicit approach is to use __all__ in __init__.py to list the classes and methods to export in a wildcard import:

# ./pacakge/__init__.py
__all__ = ['a_function_1']     # 这样,在demo.py只能调用a_function_1方法
from package.module import *

These examples use functions or methods. The same principle applies to classes.

3.3 Importing a package does not automatically import its subpackages

Normally, importing a package does not import its subpackages. With an explicit import in __init__.py, you can arrange for them to load as well. Here is an example:

$ mkdir -p a/b
$ touch a/b/c.py

Type python at the command line to open an interactive session:

import a
a                ⇒ <module 'a' (namespace)>
a.b              ⇒ AttributeError: module 'a' has no attribute 'b'
import a.b.c
a.b              ⇒ <module 'a.b' (namespace)>
a.b.c            ⇒ <module 'a.b.c' from '/home/cjs/a/b/c.py'>

Importing a alone does not automatically import a.b.c. Importing a.b.c does load its parent packages a and a.b. Now create __init__.py inside a and add import b:

Here is what happens:

import a
a                ⇒ <module 'a' (namespace)>
a.b              ⇒  <module 'b' (namespace)>
  1. 无尘粉笔. (2 Mar, 2022.). 【python】init.py文件到底是什么?. 知乎专栏. [Blog post]. Retrieved from https://zhuanlan.zhihu.com/p/474874811

  2. Ordgod_new. (28 Oct, 2020.). python构建包和模块的时候要不要加__init__.py?. CSDN. [Blog post]. Retrieved February 27, 2024, from https://blog.csdn.net/weixin_41490373/article/details/109324834

© 2024 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2024-02-27). What is __init__.py for?. https://caiborui.com/blog/2024-02-27-zh-what-is-init-py-for-entrans

@misc{borui2024-af14d2bd,
  author = {borui},
  title = {{What is __init__.py for?}},
  year = {2024},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2024-02-27-zh-what-is-init-py-for-entrans}
}