Skip to content

What is file in Python

Understand why __init__ file exists in Python packages.

This article explains why the file exists in Python packages.

There are two types of packages in python, regular and namespace packages. The former requires file whereas the latter does not. Any directory with an init python file is marked as a package by python and can be imported.

Whenever a package is imported using the import keyword or the from x import y syntax the init file is run implicitly. Generally, this file is kept empty but it can be used to achieve the following things:

  • Import submodules
  • Initialize top-level objects/variables (logger, database connections, configurations)

Working with file

First, let's create a directory named my_package and add a new file with this content

print("my_package is imported")

With this setup, we can now test if my_package can be imported using the following script

import my_package


my_package is imported

As we can see, as soon as my_package was imported the init file was run. Similarly, several submodules can be created with their own file. For example

โ”œโ”€โ”€ sub_package_1
โ”‚   โ””โ”€โ”€
โ”œโ”€โ”€ sub_package_2
โ”‚   โ””โ”€โ”€
โ””โ”€โ”€ sub_package_3

3 directories, 4 files

Similar content is written into all init files as in the my_package init file. We can then import all submodules

from my_package import sub_package_1, sub_package_2, sub_package_3


my_package is imported
sub_package_1 is imported
sub_package_2 is imported
sub_package_3 is imported

FREE VS Code / PyCharm Extensions I Use

โœ… Write cleaner code with Sourcery, instant refactoring suggestions: Link*

* This is an affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank you! ๐Ÿ™