Package structure and __init__.py

RoadmapsPython

Overview

A package is simply a folder that contains Python files. To tell Python that the folder is a package, you usually place a special file named `__init__.py` inside it. ```python # A simple file structure: # my_app/ # ├── __init__.py # └── calculator.py ``` When you import a package, Python actually runs the code inside `__init__.py` first. This makes `__init__.py` act like a front door to your package. ```python # Inside my_app/__init__.py print('The package is being imported!') VERSION = '1.0' # In another file, when you import the package: # import my_app # Output: The package is being imported! ``` The rule: **`__init__.py` marks a folder as a package and runs automatically upon import.** Think of it like a receptionist at an office. When you enter the building (import the package), the receptionist (`__init__.py`) greets you first.

It organizes your code into neat folders, preventing you from putting thousands of lines into one massive file.

Where used: Organizing large projects, Creating open-source libraries

Why learn this

Code walkthrough

# Simulate what Python does internally when importing
package_namespace = {}
# Python reads __init__.py and executes it
exec("VERSION = '2.0'", package_namespace)
# Now the package has the variable
print(package_namespace['VERSION'])

Focus: exec("VERSION = '2.0'", package_namespace)

Common mistakes

Recall questions

Understanding checks

If you imported `my_pkg` and printed `my_pkg.x`, what would it print?

10

Importing a package runs its `__init__.py` file, so the variable `x` becomes available directly on the package.

If your folder `my_app` has an empty `__init__.py` file, will Python crash when you `import my_app`?

No

`__init__.py` can be completely empty. Its mere presence is enough to tell Python that the folder is a package.

Practice tasks

Expose a variable

Modify this simulated `__init__.py` content so that it exposes an `APP_NAME` variable set to 'RetainHQ'.

Continue learning

Next: Layered architecture

Return to Python Roadmap