Python Packages - __init__ files
Python Packages - __init__ files

Python Packages - __init__ files

CMS Sprint
CMS Unit
Item ID

Link to
Related to Content (1) (Production Pages)
Tags
Type
Learning Item
Lang
EN
Parent item
Sub-item
Sharable link for students

🗂️ Unveiling the __init__.py Mystery

In our new package-driven file tree, you’ve noticed a new addition to each package: an __init__.py file. These file contain no content , but they are still a crucial piece in your project file tree.

The __init__.py file serves as the index of a package, and it helps Python recognize the directory as a package. This special file needs to exist in every package directory. Even if it's an empty file, its presence signifies to Python that the directory should be treated as a Python package.

What can you do by adding code inside __init__.py?

  1. Package Initialization: The __init__.py script runs every time we import the package. This behavior is beneficial for initializing package-level state or setting up any necessary preconditions for your package.
  2. Import Management: __init__.py can determine what is imported when the user imports the package using from storage import *.

* We will not go into these advanced use cases today, but you can read more about it here.

icon
Do I have to use __init__.py in every directory inside my project? If your directory contains Python scripts (Making it a Python Package), you need to create an empty __init__.py to avoid problems. You can skip creating an __init__.py if your directory only includes sub-directories. This use-case is known as namespace packages.

🟠 Phase 4: Our final file tree

In the final phase, our project includes three packages. Looking at it without expanding directories, we see a much more organized view of the project:

📁 CustomerConnect/
|    📁 storage/
|    📁 communication/
|    📁 users/
|    main.py

We can also use whole package import statements like this:

from communication import *

🎬 This is (not) the end…

Python packages allow us to organize our code files according to different aspects of our program. However, project file trees consist of numerous file types besides *.py files. So, how do we arrange all of them? In the upcoming learning unit, we will explore this challenge.