Python – Packages

In this article, you’ll learn to divide your code base into clean, efficient modules using Python packages. Also, you’ll learn to import and use your own or third party packages in a Python program.

What are packages?

We don’t normally keep all of our files in the same folder on our computer. For easy access, we use a well-organized structure of directories.

Similar files are stored in the same directory; for example, all of the songs could be maintained in the “music” directory. Python offers packages for directories and modules for files, similar to this.

As our application program increases in size and contains more modules, we group related modules together in one package and separate them into separate packages. This makes a project (software) simple to manage and understand conceptually.

A Python package can have sub-packages and modules, just like a directory can have subdirectories and files.

In order for Python to recognize a directory as a package, it must contain a file named init .py. This file can be left blank, although we usually include the package’s initialization code here.

Using the dot (.) operator, we can import modules from packages.

If we want to import the start module from the previous example, we can do it as follows:

Package Module Structure in Python Programming
Package Module Structure in Python Programming

Importing module from a package

Using the dot (.) operator, we can import modules from packages.

If we want to import the start module from the previous example, we can do it as follows:

import Game.Level.start

Now, if this module has a function named select difficulty(), we must refer to it by its complete name.

Game.Level.start.select_difficulty(2)

If this construct appears to be too long, we may use the following syntax to import the module without the package prefix:

from Game.Level import start

We can now call the function simply as follows:

start.select_difficulty(2)

Another option for importing only the required function (or class or variable) from a package module is to use the following syntax:

from Game.Level.start import select_difficulty

Now we can directly call this function.

select_difficulty(2)

This procedure is not recommended, despite the fact that it is easier. Using the complete namespace minimizes confusion and ensures that two identifiers with the same name do not collide.

Python searches the list of directories given in sys.path when importing packages, just as it does when searching for modules.

Leave a Comment

Your email address will not be published.