Whether you're an expert or a beginner at Python programming, you must be able to fragment your code into reusable modules. In this article, you'll learn to create, import, and reuse your Python modules across your project tree.

What Is Code Modularization, and Why Should You Use It?

Code modularization for separation of concern and code reusability is one of the basic principles of programming. Because Python is object-oriented, it's one of those languages that makes modularization easy. You can think of code modularization as assigning specific tasks to different functions or methods. Each can then works together during program execution to make a whole application.

One of the importance of code modularization is to make your code comply with the "Do Not Repeat Yourself" principle. Thus, once you create one instruction template in a dedicated method, all you'll do is apply it across relevant scripts to avoid repeating the same code all over your code base.

When you modularize a code, you give it a unique name. That name is its identity and means the next time you need to use that block of code, you only need to call out its name and not the whole code.

This practice makes your job easier and faster during a real-life project. In addition to making your code more efficient and readable, modularization improves execution speed and makes testing easier.

Since our example here uses object-oriented programming (OOP), we must discuss it briefly before moving on to creating a module. The code you intend to reuse sometimes can stand alone as an individual function. But it can also be a method in a class; that's when OOP comes into play.

Object-Oriented Programming in Python

OOP is the presentation of code in dedicated classes, instantiated as independent objects. Each object then has its attributes and methods. A class can have one or many more methods and attributes and can inherit another class.

Class attributes are the characteristics of the class, while each method is a function handling a specific instruction, which might use some class attributes. When you import and instantiate a class, you can obtain and use its attributes and methods in other programs or parts of your code base.

Creating Your Own Reusable Module in Python: A Practical Example

Now let's see how to reuse a custom word counter module in another Python file. First off, open up a command prompt to any location on your computer to start a new project. In this case, we'll use a project name of word_count. To do that, type mkdir word_count.

Next, use your preferred virtual environment tool to create a new virtual environment. If you've created one already, simply activate it. Make sure that you're still in your project's directory.

Creating project directory and making virtual environment

To create the word counter class, we first try to figure out a raw formula for calculating it. Note that while you might not have a need for a word count, it's how the idea relates to code reusability that matters for this explanation.

Next, open up a text editor to your project location and create a new Python file. In this case, the file is named counter.py; ensure that you use the correct .py extension.

Here's what the counter file looks like:

        sentence = 'how to make a reusable word counter in python'
words = sentence.split(' ')
count = sum(1 for word in words if word)
print(count) # 9

Now that the raw code works, modularize it in a dedicated Python class method to make it reusable:

        class WordCounter:
    def count_words(self, sentence):
       words = sentence.split(' ')
       count = sum(1 for word in words if word)
       return count

That's it; you've created a word counter module. Let's see how to reuse it in another Python file.

Importing the Created Module Within the Same Folder

Remember that you earlier created a file named counter.py. That file holds a class, WordCounter, which has a word counter method (count_words). If you need the counter method in a new file, import and instantiate its class in your new Python script.

Note that all your Python files must be in the same directory in this case. To ensure this, create a new Python file in the same directory where you have the wordcounter.py file.

Here's what the new file looks like:

        from counter import WordCounter
sentence = "how to import and reuse your code in Python"
counter = WordCounter()
print(counter.count_words(sentence)) # 9

You can even use the method of this class in another one via inheritance or composition. You might want to understand the fundamentals of OOP in Python to see how that works.

Reuse Your Python Module in Another Directory

If the destination file isn't in the same directory as the module file, simply reference the module using an absolute import.

To understand this further, assume you've created a new file within your project's directory. But the file you intend to import your module from is in another folder within your project's directory—let's call that folder wordcount.

To import your module from counter.py (which is now inside the wordcount folder) into a Python script in another directory:

        
import sys
sys.path.append(sys.path[0] + "/..")
from wordcount.counter import WordCounter
sentence = 'import and reuse your Python code from files with different paths'
counter = WordCounter()
print(counter.count_words(sentence)) # 11

The sys.path.append method adds the current working directory to your project's parent folder. So you might want to do this for all destination files to make your modules executable across your project tree.

During the absolute import, Python browses through the parent folder (wordcount in this case) and locates the module of interest (counter.py).

A project directory looks like this:

        
word_count
├─ destination
│ └─ destination.py
└─ wordcount
   └─ counter.py

Breaking down the folder structure: word_count is the parent directory. It contains the wordcount and destination folders that hold the counter.py and destination.py files, respectively. The counter.py script then contains the WordCounter class—when instantiated inside destination.py, it can execute its methods and attributes accordingly.

Where Does Code Reusability Work?

Modularizing and reusing your code is a best practice for any project you're running. While your project structure might be entirely different, this guide provides a basis for using custom modules across your project scripts. A similar concept applies to functions that aren't in an object. Depending on your project's layout, you can import them explicitly or absolutely, as we've done above.