What are Python modules?

Modules in Python are files containing Python code (functions, classes, variables) that can be imported and reused in other Python code files.

Key takeaways

  • Python modules help organize code, making it reusable and maintainable.

  • A module is a single .py file.

  • You can import entire modules or specific components using the import statement.

  • Python's standard library includes a vast array of built-in modules for various tasks.

Modules are essential building blocks in Python, especially when handling large projects. Simply put, modules are Python files that can be imported and utilized across different programs as reusable pieces of code. They help organize code logically and make it more maintainable. By breaking large codebases into smaller, manageable, and reusable components, modules enhance code readability and reduce redundancy.

How to make a Python module

As mentioned earlier, a Python module is simply a file containing Python code. The file name is the module name with the suffix .py added. Modules can contain functions, classes, variables, and runnable code. This code can be imported and used in other files and enables us to organize our code logically.

Here’s a sample code that we can save in a .py file and create a Python module.

# Define a function
def greet(name):
return f"Hello, {name}!"
# Define a variable
pi = 3.14159
# Define a class
class Calculator:
def add(self, a, b):
return a + b
def subtract(self, a, b):
return a - b
Sample code for a module

What can we include in a module?

There is a limitation as to what we can include in a module and what we cannot.

We can include:

  • Functions

  • Classes

  • Variables

  • Executable code (although it’s generally recommended to limit this to improve reusability)

We cannot include:

  • Code that has to be executed as part of another environment or language

  • Direct dependencies on hardware or specific OS-level features unless the module is specifically designed for them

Where should we save the module?

After writing the code for a custom module, it’s important to save it in a location accessible to the Python interpreter. By default, Python looks for modules in:

  • The directory of the script being run

  • The PYTHONPATH environment variable (if set)

  • The standard library directories

So, we can save the module in the same directory as the script that will import it, or we can place it in one of the directories specified in sys.path. To see a sample list of directories included in the Python path, run the code below.

import sys
print(sys.path) # Printing the list of paths where Python will look for modules in

In this example, sys is also a Python module.

How to import and use a Python module

To import a module, we use the import statement. Once imported, we can use the module’s functions, classes, and variables.

Syntax

To import a module, we simply write the import statement followed by the module name.

import module_name

We can also import specific components using the from keyword:

from module_name import component

Example

We have saved the module we created earlier as mymodule.py in the /usercode directory that was a part of the list of Python paths we obtained. In this code, let’s import that module and use its code.

main.py
mymodule.py
# Import the entire module
import mymodule
# Use the module's functions and classes
print(mymodule.greet("Alice")) # Output: Hello, Alice!
print(mymodule.pi) # Output: 3.14159
calc = mymodule.Calculator()
print(calc.add(5, 3)) # Output: 8
# Import a specific component
from mymodule import greet
print(greet("Bob")) # Output: Hello, Bob!

Built-in Python modules

Each version of Python comes with a rich standard library, a collection of modules that provide standardized solutions for many problems that Python programmers face. Some popular built-in modules include:

  • math: This provides access to mathematical functions

  • datetime: This supplies classes for manipulating dates and times

  • os: This provides a way of using operating system-dependent functionality

  • sys: This provides access to system-specific parameters and functions

  • random: This implements pseudo-random number generators

These modules can vary depending on the version of Python you have installed. For a complete list of built-in modules specific to your version of Python, refer to the Python Module Index.

Example

Using the math module to calculate the square root of a number:

import math
print(math.sqrt(16)) # Output: 4.0

Mastering modules is a key step in becoming a proficient Python developer. By learning how to create, import, and manage modules, you can write cleaner, more maintainable code and take full advantage of Python’s rich ecosystem.

Become a Python developer with our comprehensive learning path!

Ready to kickstart your career as a Python Developer? Our “Become a Python Developer” path is designed to take you from your first line of code to landing your first job.

This comprehensive journey offers essential knowledge, hands-on practice, interview preparation, and a mock interview, ensuring you gain practical, real-world coding skills. With our AI mentor by your side, you’ll overcome challenges with personalized support, building the confidence needed to excel in the tech industry.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is the difference between a module and a package in Python?

While a module is a single file containing Python code, a package is a collection of modules. Modules allow us to organize code into single files, and packages allow us to organize related modules into a directory structure, making it easier to manage larger codebases.

For details, have a look at “Difference between a Python module and a Python package.”


How many built-in modules are in Python?

Python’s standard library, which comes bundled with the Python installation, includes hundreds of built-in modules. The exact number of built-in modules depends on the Python version. The complete list can be obtained from the Python Module Index.


How many types of modules are there in Python?

In Python, there are two primary types of modules:

  1. Built-in modules: These come pre-installed with Python and are part of the Python standard library (e.g., math, os, random).

  2. User-defined modules: These are custom modules created by developers, which can include any combination of Python functions, classes, and variables. These modules are typically stored in .py files and can be reused across different programs.


How can I learn to code?

Learning to code can be an exciting journey, and there are many ways to get started. One effective way is to choose a platform that offers interactive, hands-on learning. Educative’s Learn to Code Skill Path takes you from an absolute beginner to a job-ready programmer. Through gamified lessons and project-focused content, you’ll engage in hands-on learning—making concepts easier to grasp and more enjoyable to apply. Our text-based courses guide you step-by-step, ensuring that you gain both the knowledge and practical experience needed to succeed in the real world.


Free Resources

Copyright ©2024 Educative, Inc. All rights reserved