DEV Community

Cover image for Python Modules: A developer's guide
DoreenNangira
DoreenNangira

Posted on

Python Modules: A developer's guide

Introduction

As a python developer, I am sure you have once encountered this term. For those who are just starting out on their python journey, don't worry because by the time you are done with this tutorial you will have a better understanding of python modules. So, let's get started.

What is a module?

A module refers to a file containing a set of defined variables, functions and statements.

Why do we use modules?

Modules help us to reuse our code. For instance, if you are writing a new program then you remember there is a code you wrote in a previous program that might be useful in your current program, you can implement the concept of modules here. We will see how to go about this in our next step.

Types of modules in python

We have two main types of modules in python. These are built-in **modules and **user-defined modules. As the name suggests, built-in modules are those that come with python when you install python in your computer. You don't need to make them. An example of a built-in module in python is the sys module which contains many predefined functions and variables. The second type of module is the user-defined module. As the name suggests, the end user is the one who makes these modules. In this tutorial we will concentrate on user-defined modules and how to make them.

How do you make a module?

First of all you need to make sure you have python installed in your machine. Open your favorite code editor then navigate to the directory or folder where you want to write your programs. Create a python file called add_0.py. This is the file that will act as our module. Add the following lines of code to your file.

#!/usr/bin/python3
def add(a, b):
    """My addition function

    Args:
        a: first integer
        b: second integer

    Returns:
        The return value. a + b
    """
    return (a + b)
Enter fullscreen mode Exit fullscreen mode

Let's go through the above code. The first line is a shebang line to tell us that this is a python script. The line says that it runs on python3 version. If you want a different version of python you can specify there. The second line defines a function named add. This function takes in two arguments which are integers. It then returns the sum of those two integers by adding them.

Good! We have now finished creating a file that will act as our module. I am sure you are now asking yourself, how do we make use of this module? Well let's do this in the next step.

Create a file that will make use of the module

While in the same directory as the one where you created your module file, create a second file called 0-add.py. Please note that you can give your file any name that you want. Add the following code in your newly created file.

#!/usr/bin/python3
from add_0 import add
a = 1
b = 2
add(a, b)
print(f"{a} + {b} = {add(a, b)}")
Enter fullscreen mode Exit fullscreen mode

Let's discuss the code we just wrote
The first line is the normal shebang line that tells us this is a python script .
The second line is where the adventure begins. You can see there is a mention of our module file which we named add_0. Since we want to use the add function in our code we need to import it from the owner. The owner here is add_0. We can look at it as a parent and a child. add_0 which is our module file is a parent. This parent has children so in this case let us say add_0 has a child called add. We want to send this child to go run some errands for us. So we will need to ask for permission from the parent first before we can give tasks to the child. So we go to the parent and ask him or her to give us the permission. This is where we use the import statement. The import here is like borrowing the child from the parent. After this we can then use the child who in our case is called add.

As we recall, add is a function that accepts two arguments and returns the sum. So in our case, we first defined two integers a and b. ** We then call the function add and pass our variables a and b to it. **add(a, b)
In the last line we now print the result.
print(f"{a} + {b} = {add(a, b)}")
The print statement takes in the values of a and b and also their sum. Here we have used a string formatter, f-strings f. This f-string here converts all our values in the print statement into strings and concatenates them. We mostly use f-strings when we want to embed variables and expressions into string literals.
You can read more about f-strings in the python official documentation [https://docs.python.org/3/tutorial/inputoutput.html]

To check if your code is running, you can now run your code. You can either run it by writing python3 0-add.py or you can convert your file to an executable file first then run it directly without python3 word. To convert it to an executable write chmod u+x 0-add.py After making it an executable file you can run it by writing ./0-add.py. You will see the result of the addition as shown below.

Image description
There are many ways of importing the module add_0.py. The above example is only one of the ways. The following code shows another way of importing our module. Make another file called para.py then add the following code:

#!/usr/bin/python3
import  add_0

a = 1
b = 2
add_0.add(a, b)
print(f"{a} + {b} = {add_0.add(a, b)}")

Enter fullscreen mode Exit fullscreen mode

The above code is almost similar to the one we wrote but in this case we are not using the from statement. We are importing our module first then when we want to use the add() function, we use dot notation. Look it as a way of calling the child of a parent. eg if we have a parent called Jane we want her child who is called Mary, we will say Jane.Mary. So it is like we are saying call Mary who is the child of Jane. If the add() function is called without referencing the parent who is add_0, our function will not execute. Python will not recognize it and you will get errors.
When you run your new file para.py, you will get the same result as you got when you ran 0-add.py as shown below.

Image description

Why do we create our files in the same directory as the module directory?

I know you must have asked yourself this question. Well, this is because when you import a module, python always looks for the name of that module within your folder. If the module you specified is not in the same folder as the file you are running, python will give you an error and say module not found.

How do you prevent the code in your script from executing when imported?

Sometimes you want your code to only run within the environment in which it resides. You don't want someone to go import it and use it in a different environment. How do we do this? Well, let's first of all try to import the script para.py from a python3 shell. Let's see how it behaves. To enter the python shell, write python3 on your terminal then press enter. You will enter the python interactive mode as shown below:

Image description
Now try importing your file para.py by writing import para. You will realize that your code executes as shown below.

Image description
To stop our script from executing when imported, we need to modify our para.py file. leave the python shell by writing exit() to go back to your initial terminal.

Image description
Open para.py file and modify it to appear as below:

Image description
Save your changes then run your file and you will realize it is still giving the required results.
Now open the python interactive shell and try importing your modified file. You will realize that this time round the code is not executing.

Image description
Good! You just prevented your file from being imported.
So let us explain how this was achieved.
The line if name == "main": is the magic. Don't forget the double underscore characters surrounding the name and main as shown in our code example.
This line says that the code below it should only be executed if the file is being run from within its original environment where it resides. If the environment is different, the code will not execute.
You can read more about name == "main" and its use in the python official documentation.

Difference between functions and modules

Some of you might find it difficult to differentiate between functions and modules. We all know that functions are reusable and that we can always avoid repetition by using functions. How do you differentiate between the two?

  • A function is meant to perform a specific task while a module is not restricted to a given task. For example, you can have a function that is only meant for adding numbers. A module on the other hand contains definitions of a mixture of many things such as functions, variables etc. A module can have many different function definitions within it.

  • Another difference is that a function resides in a file. It cannot be standalone while a module is a standalone file. A module is a whole file in itself containing different definitions.

  • A function should always be defined and it should start with a def keyword while a module does not follow any way in which it should start. Once you write your create your module file, you can always write the things you want included there.

These are just few examples of the difference but the list is long.

Conclusion

Congratulations! You have reached the end of your tutorial. I hope by this time you have a better understanding of modules. You can now start making use of them. This tutorial is meant to give you a foundation on modules. To learn more about modules, navigate to the python documentation https://docs.python.org/3/tutorial/modules.html.
See you soon! Adios!

Top comments (0)