English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Python Knowledge

Python Reference Manual

Python Packages (Package)

In this article, you will learn to use Python packages to divide your code library into clean, efficient modules. In addition, you will also learn how to import and use your own or third-party software packages in Python programs.

What is a Package (Package)?

We usually do not store all files in the same place. We use a well-organized directory hierarchy for easy access.

Similar files are stored in the same directory, for example, we can keep all songs in the 'music' directory. Similarly, Python has packages for directories and for filesmodule.

As our application grows larger, with many modules, we put similar modules in one package and different modules in different packages. This makes the project (program) easy to manage and conceptually clear.

Similarly, since the directory can contain subdirectories and files, Python packages can have sub-packages and modules.

The directory must contain a file named __init__.py for Python to treat it as a package. This file can be kept empty, but we usually put the initialization code of the package into this file.

This is an example. Suppose we are developing a game, then the possible package and module organization is shown in the figure below.

Importing modules from the package

We can use the dot (.) operator to import modules from the package.

For example, if you want to import the start module in the above example, please complete the following steps.

import Game.Level.start

Now, if the module contains a function named select_difficulty()functionWe must use the full name to refer to it.

Game.Level.start.select_difficulty(2)

If this construction looks very long, we can import the module without the package prefix as follows.

from Game.Level import start

Now, we can simply call the function as follows.

start.select_difficulty(2)

Another method to import only the required functions (or class or variable) from the module of the package is as follows.

from Game.Level.start import select_difficulty

Now we can directly call this function.

select_difficulty(2)

Although simple, it is not recommended to use this method. Use the fullnamespaceThis can avoid confusion and prevent conflicts between two identical identifier names.

When importing a package, Python checks the directory list defined in sys.path, similar tomodule search path.