Skip to content

Modules

Modular programming refers to the process of dividing large programming tasks into separate and smaller, more easily managed modules. There are several strong advantages of this programming approach:

  • simplicity - dividing the program into smaller elements, we focus on smaller problems to be solved, which makes the software development process simpler and generating fewer errors,
  • easy to maintain - if each module focuses on one task and is independent of the other, the probability of impact on other parts of the program in the case of modifications is reduced,
  • multiple use - functionality defined in one module can be imported into another module and used in it without having to write the same functions or * copy-paste * technique,
  • creating ranges and namespaces - modules help to avoid collision of names between identifiers in different parts of the program.

*.py files

If we leave the terminal in which the Python interpreter worked and re-enter it, it soon becomes apparent that all the definitions we have made so far have been forgotten. To create something more permanent, we need to save our code in a file with the appropriate extension. The Python module is any file with the extension *.py in which the code was saved. Such a module can be started and be the entrance to the entire program (e.g. it can be an input file to a newly written game).

modules

Information on modules collected:

  • In Python, every file with the *.py extension is treated as a module.
  • The *.py files contain program code.
  • The module (and thus the program) can be started in the terminal with the command python mod_name.py.
  • The program code will be executed from top to bottom.

Importing libraries into modules

As our program grows, or in the case of writing more and more advanced applications, you may need to use complex mathematical functions, write time support code on your computer or communicate with the operating system. These are frequent cases since the implementation of such functions has long taken place, and Python developers included them in the installation package so that other developers would not reinvent the wheel. To attach some additional functionality "from the outside" to our code file, we need:

  • know what we are looking for,
  • know which library implements the searched functionality,
  • import the searched library or part of it into our program.

The main Python documentation is invaluable in finding the libraries you need: Python documentation

There are four ways to import something (function, object, class, variable) from a *.py file or built-in library into another *.py file (module):

  • import module_name - imports the entire module into the module in which this instruction is located.
  • import module_name as new_name - appends the entire module named module_name to the module in which we placed this instruction, and then replaces the name within the current file with the new_name. From now on, you will be able to access the contents of the imported module only by its new local name.
  • from module_name import x - imports a variable / function / object named x from the module named module_name to the module where this instruction is located.
  • from module_name import - imports all variables, functions, objects etc. into the module where this instruction is located.

Importing libraries

There are many libraries (built-in and external) that can be used in programs after they have been attached to the project. In the examples below, we will try to import the built-in math library along with the mathematical functions it contains, and use some of them after adding the module to the project.

Method 1

Problem: we need to implement the mathematical operation of the factorial and calculate the root of a given number in our program. It turns out that this functionality has already been written and can be downloaded with the math module.

    import math

    result_fact = math.factorial(5) # Calculates strongly with 5
    print(result_fact)

    result_sqrt = math.sqrt(16) # Calculates the root of 16
    print(result_sqrt)

The import math statement has attached the entiremath module to the program. We can now access all variables, functions, classes etc. from the attached library by using the dot operator: math.sqrt(25) runs the sqrt() function from the math module.

Method 2

Sometimes there is a need to change the name of the imported module. This may be necessary when we already use the same name in the file as the name of the module that we intend to include in the program. The keyword 'as' helps in renaming the name.

    import math as mathematics

    result_fact = math.factorial(5) # Calculates strongly with 5
    print(result_fact)

    result_sqrt = mathematics.sqrt(16) # Calculates the root of 16
    print(result_sqrt)

From that moment, there is no such thing as math in our module. To all functions or variables from this library, we must refer as if this module was called mathematics.

Method 3

Instead of importing the entire library and being forced to refer to functions through the dot operator, you can opt out of including the entire package and import only those functions that interest us. Imported entities are automatically added to the file. Make sure that there is no collision of names with other variables or functions!

    from math import factorial

    result_fact = factorial(5) # Calculates strongly with 5
    print(result_fact)

    result_fact = math.factorial(5) # ERROR!

    result_sqrt = sqrt(16) # ERROR!

    result_sqrt = math.sqrt(16) # ERROR!

In the above example, only the factorial function has been imported from themath library. Nothing else has access to both the sqrt function and other goods from this module. Importantly, access to the factorial function was lost by reference to it by the dot operator. Now you can call her only by giving her name and arguments in brackets.

Method 4

In case you want to import everything from the module, but not the module itself (so that you don't have to refer to the function by the dot operator), we can use the fourth import method. However, keep in mind that this is the least recommended way. Then everything is attached to the file and all this goes to the namespace of our module, which means a possible name collision and confusion like "where did it come from?" not hard.

    from math import *

    result_fact = factorial(5) # Calculates strongly with 5
    print(result_fact)

    result_sqrt = sqrt(16) # Calculates the root of 16
    print(result_sqrt)

The dir() function

The built-in function dir() returns a list of available values ​​in our namespace.

    # Freshly running Python interpreter
    >>> dir()
    ['__builtins__', '__doc__', '__name__', '__package__']
    >>> import math
    >>> pi = math.PI
    >>> dir()
    ['__builtins__', '__doc__', '__name__', '__package__', 'math', 'pi']

With the dir() function you can find out what the python file we are currently working on has access to. As you can see, the amount of available material increases as the program runs and the next lines of code are executed.

Variables whose names begin and end with '__' are python special variables. __name__ for example, stores the name of the module that is currently being executed, and __builtins__ is the module that stores built-in functions.

Examples of built-in libraries

  • axis

Module that allows you to use the functionality of the operating system. Thanks to the variables and functions available in it, we can, for example: get to know the name of the system, get access to environment variables, create or delete directories, navigate file trees.

  • sys

Module giving access to some variables used or maintained by the interpreter and to functions strongly associated with this interpreter. For example: exiting the Python application, tracking errors, capturing I / O / errors.

  • random

A library that provides implementations of pseudo-random number generators. It allows, for example, to generate numbers for given distributions - both total and real, mix data in collections, or choose randomly values ​​from a given pool.

  • math

Importing this library will allow access to mathematical functions such as rounding numbers, calculating the largest common divisor, powers, logarithms, trigonometric functions, etc.

  • time

Provides various functions related to the calculation of elapsed time.

  • logging

This module defines functions and classes that implement a flexible event logging system for applications and libraries.

  • tkinter

A standard library that provides the tools you need to create your own Python graphical interface.

  • unittest

Module that supports test automation, sharing configuration code and closing tests, aggregating tests into collections, and testing independence in reporting.