Skip to main content

Modules

A module is a collection of functions, classes, and variables that we can use from a program. There is a large collection of modules available with the standard Python distribution.

A module can be specified as a file containing definitions and declarations from Python. The filename is the module name attached with the .py suffix. We can start by defining a simple module in a .py file. We’ll define a simple test() function inside this my module.py file that will print “This is my first module”:

You can find the following code in the my_module.py file:

def test():
print(“This is my first module”)

Within our main.py file, we can then import this file as a module and use our newly-defined test() method, like so:

You can find the following code in the main.py file:

import my_module
def main():
my_module.test()
if __name__ == ‘__main__’:
main()

When a module is imported, its content is implicitly executed by Python. It gives the module the chance to initialize some of its internal aspects. The initialization takes place only once, when the first import occurs, so the assignments done by the module aren’t repeated unnecessarily. That’s all we need in order to define a very simple Python module within our Python scripts.

Example 2

You can find the following code in the params_global_argparse.py file:

import argparse
class Parameters:
“””Global parameters”””
def __init__(self, **kwargs):
     self.param1 = kwargs.get(“param1”)
     self.param2 = kwargs.get(“param2”)
def view_parameters(input_parameters):
print(input_parameters.param1)
print(input_parameters.param2)
parser = argparse.ArgumentParser(description=’Passing parameters in an object)
parser.add_argument(-p1”, dest=”param1”, help=”parameter1”)
parser.add_argument(-p2”, dest=”param2”, help=”parameter2”)
params = parser.parse_args()
input_parameters = Parameters(param1=params.param1,param2=params.param2)
view_parameters(input_parameters)

In the previous script, we can see that with the argparse module, we obtain parameters and we encapsulate these parameters in an object with the Parameters class.