Introduction to Python Programming: Packages

1. Introduction: Why Do We Need “Packages”?

Before we start writing code, let’s imagine a real-life scenario.

Suppose your computer desktop is cluttered with all your files: photos, movies, work documents, study notes, game shortcuts… What would happen if they were all scattered on the desktop without any folders?

  1. 1. Difficult to find: You can’t locate the file named “2023 Plan.doc”.
  2. 2. Name conflicts: You can’t save two photos named “photo.jpg” unless you rename one.
  3. 3. Difficult to maintain: As more files accumulate, the desktop becomes increasingly chaotic, and eventually, you hesitate to touch anything.

To solve this problem, operating systems invented folders (Directory/Folder).

In Python programming, we face the same issue. When the code you write grows from dozens of lines to thousands or tens of thousands of lines, if you cram all the code into one file or pile all the files into one directory, the project becomes unmanageable.

The solution provided by Python is:

  • Modules: Equivalent to individual “files” (i.e., <span>.py</span> files).
  • Packages: Equivalent to “folders” used to categorize and store modules.

This article will elaborate on the principles and usage of “packages”.

2. Core Concept Analysis

Before diving into the code, we need to unify our understanding of several terms.

2.1 Modules

In Python, any file ending with <span>.py</span> is referred to as a module. A module can contain functions (features), classes (templates), or variables (data).

  • Analogy: A module is like a screwdriver in a toolbox, responsible for performing specific screw-turning tasks.

2.2 Packages

Packages are directories (folders) that contain multiple modules. They group similar modules together in the same folder for easier management.

  • Analogy: A package is like a categorized toolbox. For example, you have a box named “Home Tools” (package) that contains a “screwdriver” (Module A) and a “hammer” (Module B).

2.3 Libraries

This is usually a broader concept that refers to a collection of code released for others to use. A library may contain one package or multiple packages.

  • Analogy: The entire hardware section of IKEA.

3. Anatomy of a Package

A standard Python package structure looks like this:

my_project/              &lt;-- Project root directory
│
├── main.py              &lt;-- Main program entry (where we run the code)
│
└── my_tools/            &lt;-- This is a 【package】 (folder)
    │
    ├── __init__.py      &lt;-- 【Key】 Package identity
    │
    ├── math_tools.py    &lt;-- Module 1: Math tools
    │
    └── file_tools.py    &lt;-- Module 2: File tools

3.1 The Mysterious <span>__init__.py</span>

Note that in the structure above, the <span>my_tools</span> folder contains a strange file: <span>__init__.py</span> (note the two underscores before and after init).

  • Its function: It tells Python, “Please treat this folder as a package, not a regular folder“.
  • For beginners’ understanding: It is like a “business license” hanging at the entrance of the folder. Although in Python 3.3 and later versions, Python can still recognize the folder as a package (called a namespace package) even without this file, it is strongly recommended that beginners keep it for compatibility and clarity.
  • Its content: It can usually be empty, but it can also contain some initialization code (to be introduced later).

4. Practical Exercise: Building a “Smart Home” Package from Scratch

To help you get started, we will simulate writing a simple smart home control system.

Step 1: Create the Directory Structure

Please create a folder on your computer with the following structure:

smart_home_project/          &lt;-- Main folder
│
├── main.py                  &lt;-- Main control program
│
└── home_devices/            &lt;-- Our package (storing device control code)
    │
    ├── __init__.py          &lt;-- Can be an empty file
    │
    ├── light.py             &lt;-- Module for controlling lights
    │
    └── audio.py             &lt;-- Module for controlling audio

Step 2: Write Module Code

Please write the following code in the corresponding files.

1. Write <span>home_devices/light.py</span> (Light Control Module)

# File name: home_devices/light.py

def turn_on():
    """Function to turn on the lights"""
    print("【Lighting System】: The lights are on, the room is brighter.")

def turn_off():
    """Function to turn off the lights"""
    print("【Lighting System】: The lights are off, it's pitch dark.")

def change_color(color):
    """Function to change the light color"""
    print(f"【Lighting System】: The ambient light color has been changed to {color}.")

2. Write <span>home_devices/audio.py</span> (Audio Control Module)

# File name: home_devices/audio.py

def play_music(song_name):
    """Function to play music"""
    print(f"【Audio System】: Playing the song —《{song_name}》。")

def stop_music():
    """Function to stop music"""
    print("【Audio System】: Music has been paused.")

3. Handle <span>home_devices/__init__.py</span> (currently keep it as an empty file, or create a new empty text file and rename it to <span>__init__.py</span>

Step 3: Call the Package in the Main Program

Now, let’s return to the <span>main.py</span> in the root directory and try to use the package we just wrote.

This involves Python’s most important keyword:<span>import</span> (to import).

Method A: Regular Import Method (import …)

# File name: main.py

# Syntax structure: import package_name.module_name
import home_devices.light
import home_devices.audio

print("=== Smart Home System Starting ===")

# When calling, you need to write the full path: package_name.module_name.function_name()
home_devices.light.turn_on()
home_devices.light.change_color("warm yellow")
home_devices.audio.play_music("Mozart's Serenade")

print("=== System Test Completed ===")

Method B: Convenient Import Method (from … import …)

If you find it tedious to write <span>home_devices.light</span> every time, you can use the <span>from</span> statement.

# File name: main.py

# Syntax structure: from package_name.module_name import function_name
from home_devices.light import turn_off
from home_devices.audio import stop_music

# You can also give the module a "nickname" (alias) using the as keyword
from home_devices import light as my_light

print("=== Goodnight Mode Starting ===")

# Directly use the function name without prefix
turn_off()
stop_music()

# Call using the alias
my_light.turn_on() # Because I suddenly wanted to go to the bathroom and turned on the light again

print("=== Demonstrating the use of alias ===")

5. Advanced Knowledge: The Wonderful Use of <span>__init__.py</span>

We just mentioned that <span>__init__.py</span> can be empty, but it actually has more advanced uses: controlling the exposed content of the package.

Suppose your package contains dozens of modules, and users don’t know which one to use. You can simplify user operations by editing <span>__init__.py</span>.

Modify <span>home_devices/__init__.py</span>:

# File name: home_devices/__init__.py

print("-&gt; Initializing smart home components...")

# Import the turn_on function from the current package's light module
from .light import turn_on
# Import the play_music function from the current package's audio module

# Here, the . indicates "current directory"

Modified <span>main.py</span> calling method:

# File name: main.py

# Now we can directly import functions from the "package" without going through the "modules"
# This means skipping the light.py and audio.py layers because we bridged them in __init__.py
from home_devices import turn_on, play_music

turn_on()
play_music("Beethoven's Fifth Symphony")

Principle Analysis: When Python imports a package, it first executes the <span>__init__.py</span> file under that package. The import statements we wrote inside elevate the deeper functionalities to the top level of the package, making it easier for users to use.

6. Standing on the Shoulders of Giants: Third-Party Packages (PyPI and pip)

Having learned how to write packages yourself, you must know that Python’s greatest strength lies in its ecosystem.

Python programmers worldwide have written millions of packages and uploaded them to a public repository called PyPI (Python Package Index).

As a beginner, you don’t need to reinvent the wheel; you can directly download packages written by others to use.

How to Install Third-Party Packages?

Use the <span>pip</span> tool in your computer’s terminal (Terminal or CMD). It is Python’s package manager (equivalent to an “app store” on your phone).

Example: Install a popular third-party package <span>requests</span> (for accessing web pages)

  1. 1. Open the command line/terminal.
  2. 2. Enter the command:
    pip install requests
  3. 3. Wait for the installation to complete.

Using Third-Party Packages:

# File name: test_internet.py

# Import it just like you would import your own package
import requests

# Use the powerful features written by others
response = requests.get("https://www.python.org")

print("The access status code of the Python official website is:", response.status_code)
# Output 200 indicates success

7. Common Issues and Pitfalls Guide (FAQ)

For beginners, there are often the following issues when using packages, so please pay attention:

Q1: What does the error <span>ModuleNotFoundError: No module named 'xxx'</span> mean?

  • Reason: Python cannot find the package or module you mentioned.
  • Solution:
  1. 1. Check if the file name is misspelled.
  2. 2. Check if the module is in the current running directory or in Python’s search path.
  3. 3. If it’s a third-party package, check if you forgot to run <span>pip install xxx</span>.

Q2: Is there any naming convention?

  • Norm: It is recommended that package names and module names be all lowercase, with words separated by underscores (e.g., <span>smart_home</span> instead of <span>SmartHome</span>).
  • Taboo: Never name your files with the names of Python’s standard libraries!
    • Incorrect Example: You created a file called <span>math.py</span> or <span>code.py</span>.
    • Consequence: When you try to <span>import math</span>, Python will import your fake file instead of the built-in math library, causing the program to crash.

Q3: What is Circular Import?

  • Phenomenon: Module A imports <span>B</span>, and Module B imports <span>A</span>.
  • Result: This is a deadlock problem of “the chicken or the egg”, and the program will throw an error.
  • Advice: As a beginner, try to clarify dependencies and avoid mutual references between two modules. If you must reference, try placing the import statement inside a function.

8. Conclusion

Congratulations! You have now mastered a crucial aspect of Python programming.

Let’s review what we have learned:

  1. 1. Modules are individual <span>.py</span> files, while packages are folders containing <span>__init__.py</span>.
  2. 2. Using packages can help organize messy code, just like tidying up your computer desktop.
  3. 3. You can flexibly use these features through <span>import</span> and <span>from ... import</span>.
  4. 4. <span>pip</span> is your good helper, helping you access the wisdom contributed by developers worldwide.

Next Steps: Don’t just read the code; make sure to open your code editor (like VS Code, PyCharm), create folders, new files, type in the code, and run it according to the “Smart Home” example in the text. Programming is an art of practice; only by doing can you truly understand it.

Wishing you great success on your journey of learning Python!

Leave a Comment