A switch towards a more professional python coding practice is separating every functionality in a separate file, and thatâs called modules.
Hello everyone and welcome to the article where we are going to learn everything that you need to know about python modules.
Some of the questions we will answer in this article:-
- What is a module in python?
- How do I create a Python module?
- How do I import objects of a module?
- What happens when a module is called?
- How many modules are in Python?
With every topic or question, we will apply what we learned in examples to make sure the concept is acquired.
First of all, we choose python as the programming language for many reasons, that includes: code readability and simplicity, a wide community, and needing fewer lines to write the same functionality as another language such as C.
In this article, we will assume that you already know the concept of functions and use them in your coding practice. if you want to learn about Python functions read our guide on Python Functions: The Definitive Guide.
Python Modules: The Definitive Guide đđ
What is a module in python?
In simple words, a Python module is a python namespace that will be called and used in another one. The module can be made of variables, functions, and classes, usually, that have a certain common ground or used for specific functionality.
How do I create a python module?
Letâs create a folder called âObject detectionâ where we will write our scripts. The folder contains 2 scripts, the first-named âTakeImage.pyâ and the second âDetectObject.pyâ
Each of those â.pyâ files is a python namespace that we created using an IDE (like sublime, Atom, VS CodeâŠ) or a simple text editor.
Inside the âTakeImage.pyâ file we will write the script that will take an image from a camera, which is the following.
The namespace contains three functions, âsetup_Cameraâ will be called at the beginning of our script to make the camera ready, and then depending on whether we need an RGB or grayscale image, we will call the other functions to return an image.
Each one of those functions can be called separately and in another namespace.
Now in the âDetectObject.pyâ file is where the magic happens. We will import the TakeImage module we created using âImport TakeImageâ, note that this only works if both files are in the same folder. Now that the import is done, we can use all the functions of âTakeImage.pyâ inside âDetectObject.pyâ.
In this example, when the script is executed, line 18 is called, which calls the function âmain ()â.
Now we need to setup the camera, to do this we will call the function âsetup_camera ()â from the âTakeImageâ module using the moduleâs name then the function we need. In this example it will be âTakeImage.setup_Camera ()â, then the function âdetect ()â is called.
The second time we will use the module âTakeImageâ to call the functions âcapture_RGB ()â and âcapture_grey ()â, and based on their results we will call the function âcheck_for_objectâ , inside the print statement.
In this example, the âDetecObjectâ module imports the âTakeImageâ module, which enables it to use functions implemented in that module.
How do I import objects of a module?
We already saw how to import the entire module and use its functions, but if we want to use only a specific object from the module, we can simply import this one only using âfrom TakeImage import setup_cameraâ and now it can be used without the âTakeImageâ keyword.
In this example, it was easy to call the functions using the âTakeImage.captureRGB()â format, but if our module contains hundreds of functions and we need to call them several times, we can use the âfrom TakeImage import * â.
Now all the objects from the module are imported and we can use them directly without writing âTakeImage.â. But you should be attentive as this can get tricky. This example below will directly show you how itâs done.
Custom import name
Sometimes we can import a module under another name than its original one. This can be used in many situations, for example when the moduleâs name is long or will be used a lot.
We can use short abbreviations instead of the original name. One of the widely used module is called ânumpyâ and is often import as ânpâ using âimport numpy as npâ. Now when we need a specific object from the ânumpyâ module we will write ânp.â instead of ânumpy.â
In this example, we import ânumpyâ and then used two objects from this module. To create a ânumpy arrayâ we used ânp.arrayâ and then to find the biggest number in this array we used the function ânp.maxâ.
Note that importing numpy wonât work unless youâve already installed it. To do so, open a terminal or CMD, and install it using pip by writing:
âPIP install numpyâ.
This will install numpy all itâs dependencies and you will be able to use it anywhere.
The second usage of import modules with custom names is when we have similar functionality between two modules.
This could be useful when we want to import a module conditionally to use the same name later in the code. So, depending on a certain condition we may import a module or another, both under the same name.
In this example, we are importing the module âdraw_rectangleâ or âdraw_circleâ depending on a variable called ânumber_edgesâ, both modules are imported under the name âdrawâ.
Now in the rest of our code, we can use âdrawâ considering we already made the choice of a module at the beginning. This could be useful if we have many shapes in a bigger code and both modules have the same objects, we will always use the âdrawâ keyword which will be faster and more efficient.
How to import modules from a different folder?
When we create custom modules, we could tell the Python interpreter where to look for them, aside from the default, which is the local directory and the built-in modules. You could either use the environment variable PYTHONPATH to specify additional directories to look for modules in, like this:
âPYTHONPATH=/my_folder python my_module.pyâ
Another method is the sys.path.append function. You may execute it before running an import command:
âsys.path.append(â/my_folderâ)â
Writing a real example
Now that we got all the theory, itâs time to create our own small project. We will create two python files named âcalculate.pyâ and ânumbers.pyâ. Inside âcalculate.pyâ we will create the functions that will be used in the ânumbers.pyâ namespace.
First of all, we will create both files with their respective names and place them in the same folder.
Inside âcalculate.pyâ, we will define two functions, letâs go threw them and what each one does.
The âaddâ function, takes one argument, called âaâ. The object of this function is to return the summation of all the elements of the array âaâ.
To store the value in every iteration, we will use a variable that we defined as âsumâ that is initialized with the value 0 because it doesnât affect addition.
Now we will use a for loop to iterate threw all the elements of the array, and in every iteration, we will add the value âiâ, which is the value of the array in this step, to the variable sum.
Note that writing âsum+=iâ is similar to âsum = sum + iâ but in more professional way. Finally, when the loop is over, we will return the variable âsumâ.
The second function is pretty similar to the first one. We will define it as âmultiplyâ, it also takes one array as an argument and needs to return the multiplication of all the elements inside it.
Just like we did in the âaddâ function, we will iterate threw all the elements of the array and in every step, we will multiply our âmultâ variable with the corresponding element.
Note that in multiplication we canât use 0 as an initial value because itâs value wonât change in multiplication, thatâs why we will start with 1, which is neutral in multiplication.
Now our module is ready and itâs time to use it in another namespace.
Inside the ânumbers.pyâ namespace we will write the following:
In the first line we will import the module we already created under a new name because itâs too long. So, from now we can just write âcalâ instead of âcalculateâ.
We start by creating an array called numb which contains the values that we will use later on. The user is prompted to choose between addition or multiplication by entering 1 or 2.
Note that getting an input from the user will not work in the sublime ide, we will need to run it from a command line or terminal.
This input will be converted to an integer because it is returned as a string from the input function. Now depending on whether the user entered 1 or 2 we will call a function from the calculate module.
In case the user pressed 1, we will call the function add and pass ânumbâ as an argument, it will return the summation of all itâs elements. Similarly, will happen if 2 is pressed and the multiplication will be returned.
This returned element is stored in a variable called âresultâ in both cases so we can print it later on. We could have directly printed the result in every if condition, both ways have the same output.
You may have noticed the try and except keywords used here, those are for error handling. If the user entered a number different than 1 or 2, none of the conditions will be met and the âresultâ variable wonât be created.
When calling the print function, we passed the âresultâ variable, so if it wasnât created, we will have an error and a crash will happen. To avoid this, we will use the âtry and exceptâ keywords.
The lines in the âtryâ block are first executed, if an error happens, instead of crashing, the lines in the âexceptâ block will be executed, in our case we will print a message for the user to know that he entered a wrong number.
When executing the following script, you should have a similar result:
Python bytecode files
You may have noticed that when importing a module, like TakeImage a â.pycâ file appears, with the same name but an extension of â.pycâ instead of â.pyâ, this is a compiled Python file.
Python compiles files into Python bytecode so that it wonât have to parse the files each time modules are loaded. The first time a module is imported this bytecode file is created and then it gets loaded instead of the â.pyâ file.
The user isnât required to do any actions for this process to happen, itâs done automatically.
Some useful functions
When using built-in python modules, sometimes we often donât know the objects they contain. To check the list of a moduleâs objects we can use the âdir ()â function and as argument write the moduleâs name.
And then when we choose the object, we can get more information by using the âhelp ()â function and passing the specific object.
For example, in the following we imported ânumpyâ and then called the âhelpâ function for the âcosâ object from the ânumpyâ module.
Tasks to practice
To make sure that you completely mastered this topic, here are some tasks to try by yourself
- Create two modules in a folder and then import them in a namespace located in another folder.
- Create a module that you will import in a namespace in a different folder, then use it as a module to import in a third namespace in a new folder.
- Explore different built-in python modules likes numpy, matplotlib, pandas.
This article comes to an end here, I hope everything was clear. Now itâs time to explore our video tutorial.
If you have any questions donât hesitate to drop a comment in the section below.