Posted on 6/18/2025 5:54:24 PM by Admin

Organizing Code Efficiently in Python: Modules and Packages

In one of the previous articles, we learned how to break down complex programs into smaller, more manageable units called functions. This approach works well with smaller programs, but as your project grows, the code size and complexity increase. Creating many functions within a single program can make your code difficult to navigate, prone to naming conflicts, and impossible to manage. Imagine having hundreds of functions within a single file.

This is where the need for modules and packages arises that allow us to organize our code more efficiently. These allow you to structure your project code into multiple files and directories, making your programs more manageable, readable, and reusable. In this article, we will learn how to create our own modules, import them, and explore Python's built-in modules.


Modules in Python

A module in Python is a simple .py file with reusable variables, functions, and classes. The main purpose of modules is to organize code into reusable units. Instead of defining hundreds of functions in a single file, collect the related methods in a single file. Think of a module as a box. When shifting a house, you put kitchenware in one box, books in another, and showpieces in a separate box. Each box contains a separate set of related items. Similarly, a module contains related items, i.e., variables, functions, and classes.

Example:

Remember we created a simple calculator in our previous lesson? We can generalize the methods defined in that program by saving it as a .py file and importing it into other programs.


# math_operations.py

def addition(number_1, number_2):
    return number_1 + number_2

def subtract(number_1, number_2):
    return number_1 - number_2

PI = 3.14159

E = 2.71828

Our `math_operations.py` is a module now that contains two methods and 2 variables.

Creating and Importing a Module

Any file that contains functions, variables, or classes saved as .py can be treated as a module, and its functions, classes, and variables can reused in other programs by importing it.

Creating a Module

For practice, let's create a simple greetings.py module.


# greetings.py
def greeting(name = "User"):
    print("Hello ", name, ",")
    print("Hope you are having a great day!")

Importing a Module

To use the methods, variables, and classes defined within a module, you need to import them. We use the 'import' keyword to do so:

Syntax:


import module_name

Example:

Let's import our greetings module in main.py:


import greetings

greetings.greeting("John")

Output:


Hello  John ,

Hope you are having a great day!

In the above code example, you can see that we have to call the module name every time we call a function defined within it. This might become hectic since some modules might have bigger names, and you may need to call the members from it multiple times. To avoid this issue, you can use the alias for the module name as follows:

Syntax:


import module_name as alias

Example:


import greetings as grt

grt.greeting("John")

The above code works the same as the previous one.

Importing Only Specific Definitions

If you want to import the specific definitions from a module, you can do so using the from keyword:


from module_name import definition

This also negates the need to call the module name while calling the attribute as well.

Example:


from greetings import greeting

greeting("John")  # No need to call the module name or module object.

Tip: You can import multiple members from a module using commas. E.g., from greeting import greeting, welcome_message

Built-In Modules

In addition to custom modules, Python has a huge library of built-in modules that we can use for our convenience. Python's founders developed some of these modules, whereas the others were created by Python programmers. To use these modules, we do not need to install anything explicitly. They are downloaded and installed automatically as they are part of Python's standard library. Let's look into Python's most used modules.

math

This module provides the mathematical functions and constants that you can import and use to perform calculations without defining the formulas.


import math
print(math.pow(2, 5)) # Output: 32
print(math.pi)      # Output: 3.141592653589793

Output:


32.0
3.141592653589793

random

This is used to generate random randoms. It is highly applicable in programs where you need to generate random numbers, like guessing the number game, choosing a random object from a given list, etc.


import random
print(random.randint(1, 10))   # Output: a random integer between 1 and 10 (inclusive)
print(random.choice(["red", "green", "blue"])) # Output: a random color

The above code will generate a different result every time you run it.

Output:


5

blue


Packages in Python

As your programs grow further and already have a few modules, you will need a way to organize these modules themselves. So, simply put, a package is a collection of modules that combines related modules into shared directories. They help you structure larger applications into logical sub-sections to prevent naming conflicts among different parts of big projects.

Importing From Packages

To import modules, functions, and other members from packages, we use the import keyword with the dot (.) operator to call the subsequent members following the package name.

Syntax:


import package_name.module.member_name

You can also import an entire module with an alias as follows:


import package_name.module as alias

Finally, you can also use the 'from' syntax:


from package_name.module_name import member


Introduction to pip and PyPI

There are hundreds of third-party libraries developed by fellow Python programmers that you can access and use. pip is the Python installer that allows you to install packages from the Python Package Index (PyPI) and other repositories using a terminal or command prompt. PyPI is an official third-party package repository that contains the libraries developed by other programmers.

Installing a Package with a pip

Open your terminal (Linux/macOS) or the Command Prompt (Windows) and run the following command with proper package name:


pip install package_name

Please note that directly installing packages globally can lead to conflicts between the programs that need different versions of the same package. Therefore, using virtual environments to manage such dependencies is crucial and recommended.

Woohoo! We are moving towards advanced Python really fast. Hopefully, you are practicing a lot while covering these topics because without practice, learning a programming language is impossible. We have already covered almost all the basic concepts in Python programming. The next couple of articles will cover Object Oriented Programming in Python, which you will not find difficult if you have a strong concept of the topics we have covered so far.


Sharpen Your Skills with These Next Guides