Introduction
Python is one of the most commonly used programming languages across the world. Modules are a critical part of the Python code. A module is simply a .py file in the context of Python 3. This means that you can refer to any Python file as a module.
It is possible for you to obtain these modules through the preformed library. You can take a look at the Python Standard Library to learn more. These are installed on your system when you install Python. In other situations, you can install these modules using the Python package manager pip. But what if you want to create a custom module? If such is the case, then you will be glad to know that you can make your own modules in Python.
In this detailed guide, we will outline the steps you need to follow to write and import modules in Python 3.
Prerequisites
Before we begin, you would need to make sure that you have Python 3 installed and a programming environment set up. You can follow our tutorial on installing Python 3 and setting up a local programming environment on Ubuntu 16.04 to complete the installation in case you don’t have it ready.
How to Write a Module?
Let’s begin with the writing of a module. You would write a module just like you would compose any other Python file. A typical module comprises the definitions of the functions, classes, and variables. Subsequently, you can use the module to apply to other Python programs.
To help you understand, let’s consider an example. Let’s say we want to make a file named
hello.py. We will later import this onto another file as well. The first step in the process is to make a function. This function will serve to print
Hello, World! like this:
1 2 3 |
# Define a function def world(): print("Hello, World!") |
At this point, running the python hello.py command will give you no result. This is because we have not yet given any instructions to the program. To make it work, we need to import the module.
How to Import a Module?
In order to import your module to make it a function, you need to make a second file in the same directory. We shall call this new file
main_program.py. The reason why both files must be in the same directory is that we need to guide the program where to find the module. This is applicable to any new, custom module that is not built-in:
1 2 3 4 5 |
# Import hello module import hello # Call function hello.world() |
We used dot notation for the module name to call the function. Another way to do this is to use the
from...import method. Here, we will call the function as
world() by importing the module as
from hello import world. Finally, you can run the command:
1 |
python main_program.py |
The command will show you the following output:
1 2 |
Output: Hello, World! |
Adding Variables to a Module
Next, we shall see how to add variables to the module by putting definitions in the module:
1 2 3 4 5 6 |
# Define a function def world(): print("Hello, World!") # Define a variable shark = "Sammy" |
Subsequently, you will call the variable in the
print() function. We will call it within the
main_program.py file:
1 2 3 4 5 6 7 |
# Import hello module import hello # Call function hello.world() # Print variable print(hello.shark) |
Running the program will show this output:
1 2 3 |
Output: Hello, World! Sammy |
Adding a Class to a Module
Lastly, we will see how you can define a class in your file for the module. Continuing our example, we will be making a new class called
Octopus in the
hello.py file. We will also assign it the attributes of
name and
color. Then, we will add a function to make it printable:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# Define a function def world(): print("Hello, World!") # Define a variable shark = "Sammy" # Define a class class Octopus: def __init__(self, name, color): self.color = color self.name = name def tell_me_about_the_octopus(self): print("This octopus is " + self.color + ".") print(self.name + " is the octopus's name.") |
Next, you must add the class near the end of the
main_program.py file:
1 2 3 4 5 6 7 8 9 10 11 12 |
# Import hello module import hello # Call function hello.world() # Print variable print(hello.shark) # Call class jesse = hello.Octopus("Jesse", "orange") jesse.tell_me_about_the_octopus() |
You can call the class with the
hello.Octopus() command. It will show you the functions and attributes of the Octopus class in the namespace of the file. As such, you may write
jesse.tell_me_about_the_octopus() in the last line without invoking
hello. It is also possible to call an individual attribute of the class without using
hello. For example, you can simply run
jesse.color. When you run the program, it will show the following output:
1 2 3 4 5 |
Output: Hello, World! Sammy This octopus is orange. Jesse is the octopus's name. |
Implementing Code with Modules
Where you can use modules to specify definitions, you can also use them to implement code. Let’s say we want to implement the
world() function. We will rewrite our initial
hello.py file completely:
1 2 3 4 5 6 |
# Define a function def world(): print("Hello, World!") # Call function within module world() |
From the
main_program.py file, we will delete everything except the import statement, leaving behind the following:
1 2 |
# Import hello module import hello |
Running the main program file will give you this output since the program implements and executes the
world() function:
1 2 |
Output: Hello, World! |
How to Access a Module from Another Directory?
Now that you know how to create and modify modules, you need to know how to access them from another directory. This is useful when you need to use a given module on another project. There are two ways to do so which we will explain below.
-
Appending Paths
The first method is to activate the module path using the programming files that are already using the module. Unfortunately, doing so does not mean the module will be available across the whole system. Hence, it is only considered a temporary solution. It is often employed during the development phase of the project.
You can start the appending process by importing the sys module and other important modules you need to use. We will import them to the main program file. You can find the sys module in the Python Standard Library. You need it because it contains the basic parameters and functions specific to your system.
Consider our previous example once again. Let’s say the
hello.py file is on the
/usr/sammy/ path and the
main_program.py file is in another directory. We will import the
hello module in the
main_program.py file first using the sys module. Next, we will append
/usr/sammy/ to the path:
1 2 3 4 5 6 |
import sys sys.path.append('/usr/sammy/') import hello ... |
If you set the path correctly, the main_program.py file will run easily without errors. You will receive the same output as you did when both files were in the same directory.
-
Python Path
The other option you can take is the Python path. Here, you would add the module itself to a path which Python checks for modules and packages. As you can probably infer, this makes the module available system-wide, making it a viable permanent solution.
To do this, you need to figure out where Python is looking for modules. You will have to run the Python interpreter from the programming environment which looks like this:
1 |
python |
The next step is to import the
sys module:
1 |
>>> import sys |
Next, print out the system path:
1 |
>>> print(sys.path) |
Now, you will see a system path as your output. There will be at least one. However, there may be several in a programming environment. In the list, locate the environment that you are using. Keep in mind that you may want to add the module to the main system Python path as well. This is what it will look like:
1 2 |
Output: '/usr/sammy/my_env/lib/python3.5/site-packages' |
Finally, move the
hello.py file into this directory and import the module as follows:
1 2 |
import hello ... |
You are successful in your attempt if the program runs the file without producing any errors. As a result of this process, you will be able to access the module from any directory on your system.
Conclusion
The aim of this tutorial was to help you familiarize yourself with Python module writing. It is very similar to how you would write any Python .py file. We first talked about what a Python module and associated features actually are. Then, we discovered how to apply these definitions in other programming files in Python. Finally, we figured out the details of module accessibility. Now you know how to write modules in Python 3 as well as access them.
To further build on your knowledge about the Python programming language, refer to our blog for more resources:
- Python 3: A Guide on Converting Data Types
- Loops in Python 3: Using Break, Continue, and Pass Statements
- Using Python 3 String Formatters
Happy Computing!
- How to Deploy WordPress with Persistent Volume on Kubernetes Cluster - March 17, 2023
- Deploying Applications on Kubernetes Using Argo CD and GitOps - October 26, 2022
- Using Node.js Modules with npm and package.json: A Tutorial - October 6, 2022
- Using Ansible to Install and Configure WordPress with LAMP on Ubuntu - September 23, 2022
- Creating Views in the Django Web Application Framework - September 22, 2022