Package structure and __init__.py
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
- Every real-world project uses folders to separate code.
- It helps you avoid ModuleNotFoundError when trying to import your own files.
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
- Putting too much code in __init__.py: If you write all your logic inside `__init__.py`, the file gets too large. It should only be used to import things from other files, not to write full functions.
- Forgetting __init__.py in older versions: While modern Python allows folders without `__init__.py` (called namespace packages), tools often get confused without it. Always include it to be safe.
Recall questions
- Explain what a package is in your own words, as if to a classmate.
- What happens automatically when you import a package?
- Why should you avoid putting too much code inside __init__.py?
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