LibraryCreating your own modules

Creating your own modules

Learn about Creating your own modules as part of Python Mastery for Data Science and AI Development

Mastering Python: Creating Your Own Modules

As you delve deeper into Python for Data Science and AI, the ability to organize your code into reusable modules is crucial. Modules allow you to break down complex programs into smaller, manageable, and more maintainable units. This not only improves code readability but also promotes code reuse across different projects.

What is a Python Module?

At its core, a Python module is simply a file containing Python definitions and statements. The file name is the module name with the suffix

code
.py
appended. Modules can contain functions, classes, and variables. They serve as a way to logically organize Python code.

What is the fundamental characteristic of a Python module?

A Python module is a file containing Python definitions and statements, with the file name ending in .py.

Why Create Your Own Modules?

Creating your own modules offers several significant advantages:

  • Organization: Keeps related code together, making projects easier to navigate.
  • Reusability: Allows you to use the same code in multiple projects without rewriting it.
  • Maintainability: Changes to one module don't necessarily affect others, simplifying updates.
  • Namespace Management: Helps avoid naming conflicts by encapsulating code within a module's namespace.

Think of modules as specialized toolboxes. Instead of carrying all your tools everywhere, you grab the specific toolbox you need for a particular job.

Creating a Simple Module

Let's create a simple module named

code
my_math_operations.py
with a couple of functions.

Create a file named my_math_operations.py and add the following Python code:

# my_math_operations.py

def add(a, b):
    """Adds two numbers."""
    return a + b

def subtract(a, b):
    """Subtracts the second number from the first."""
    return a - b

PI = 3.14159

This code defines two functions, add and subtract, and a constant PI. These are now part of the my_math_operations module.

📚

Text-based content

Library pages focus on text content

Using Your Custom Module

To use the functions and variables from your module, you need to import it into another Python script. Create a new file, for example,

code
main_script.py
, in the same directory.

Here are a few ways to import and use your module:

1. Import the entire module:

python
500 italic"># main_script.py
400">"text-blue-400 font-medium">import my_math_operations
result_add = my_math_operations.400">add(10, 5)
result_sub = my_math_operations.400">subtract(10, 5)
400">print(f400">"Addition: {result_add}")
400">print(f400">"Subtraction: {result_sub}")
400">print(f400">"PI value: {my_math_operations.PI}")

2. Import specific items from the module:

python
500 italic"># main_script.py
400">"text-blue-400 font-medium">from my_math_operations 400">"text-blue-400 font-medium">import add, PI
result_add = 400">add(20, 7)
400">print(f400">"Addition: {result_add}")
400">print(f400">"PI value: {PI}")

3. Import with an alias:

python
500 italic"># main_script.py
400">"text-blue-400 font-medium">import my_math_operations 400">"text-blue-400 font-medium">as mmo
result_add = mmo.400">add(15, 3)
400">print(f400">"Addition: {result_add}")
What is the primary benefit of using import module_name as alias?

It allows you to use a shorter, more convenient name to refer to the module, especially useful for long module names or when you want to avoid naming conflicts.

The `__name__` Variable

Every Python module has a special built-in variable called

code
__name__
. When a Python script is executed, the interpreter assigns a value to
code
__name__
based on how the script is being used.

  • If the script is run directly,
    code
    __name__
    is set to the string
    code
    '__main__'
    .
  • If the script is imported as a module into another script,
    code
    __name__
    is set to the module's name (e.g.,
    code
    'my_math_operations'
    ).

This allows you to write code that only runs when the module is executed directly, not when it's imported.

Let's add this to our

code
my_math_operations.py
file:

python
500 italic"># my_math_operations.py
400">"text-blue-400 font-medium">def 400">add(a, b):
400">""400">"Adds two numbers."400">""
400">"text-blue-400 font-medium">return a + b
400">"text-blue-400 font-medium">def 400">subtract(a, b):
400">""400">"Subtracts the second number 400 font-medium400">">from the first."400">""
400">"text-blue-400 font-medium">return a - b
PI = 3.14159
400">"text-blue-400 font-medium">if 400">"text-blue-400 font-medium">__name__ == 400">"400 font-medium400">">__main__":
400">print(400">"This code runs only when my_math_operations.py is executed directly.")
400">print(f400">"Testing 400">add(5, 3): {400">add(5, 3)}")
400">print(f400">"Testing 400">subtract(10, 4): {400">subtract(10, 4)}")

Now

Organizing Modules into Packages

As your projects grow, you might want to organize multiple related modules into a directory structure called a package. A package is a directory containing Python modules and a special

code
__init__.py
file. The
code
__init__.py
file can be empty, but its presence tells Python that the directory should be treated as a package. This further enhances code organization and reusability.

What is the purpose of the __init__.py file in a Python package?

It signifies that the directory should be treated as a Python package, allowing for the organization of multiple modules within that directory.

Learning Resources

Python Modules: The Official Python Tutorial(documentation)

The official Python documentation provides a comprehensive overview of modules, including how to create, import, and use them effectively.

Python Packages: A Deep Dive(blog)

This article from Real Python explains the concept of Python packages, how to structure them, and best practices for organizing your code.

Understanding Python's `__name__ == '__main__'`(blog)

A clear explanation of the `__name__ == '__main__'` idiom and its importance in writing reusable Python code.

Python Import System Explained(blog)

This tutorial covers the intricacies of Python's import system, including how Python finds modules and packages.

Python Modules and Packages - GeeksforGeeks(blog)

An introductory guide to Python modules and packages, covering basic concepts and examples.

Python Module Basics(tutorial)

Programiz offers a straightforward tutorial on creating and using Python modules with practical examples.

Python's `__init__.py` Explained(blog)

This guide explains the role of `__init__.py` in creating Python packages and how to structure them.

Effective Python: 90 Specific Ways to Write Better Python(book)

While a book, this resource often has online discussions and summaries that cover module best practices. Look for chapters on code organization and reusability.

Python Module System - PyCon Talk(video)

A PyCon talk that delves into the Python module system, offering insights from experienced developers.

Python Standard Library Overview(documentation)

Familiarize yourself with Python's extensive standard library, which is a collection of pre-built modules you can import and use.