Python - Modules - What are it? How to use?

Python - Modules - What are it? How to use?

By lingy | Lingy | 2 Jan 2022


Imagine the following situation: you open an email from your boss with the title "urgent". It says:

hey guy

Our programmer Mark wrote a snippet of code in the module  pessoas/clientes.py, but it has a bug. To solve it, you should look for a called module  financeiro.py and import the function from it  imposto_de_renda, using it instead of that atrocity that Mark did.

Let me know when it's all over.

At first, it appears to be a trivial task. But what are modules. How can I use them? And import? How do you import a module?

What are modules?

Think of modules as small sets of code that you can add to your program to perform certain tasks. The module  os, for example, is used to access operating system functions, such as reading and writing to files, while the module is  math used to perform various mathematical operations.

These are some modules that come by default in Python:

 

Besides these, there are still some thousands of libraries containing several modules included for you to add to your programs for the most diverse functionalities.

What are these modules for?

At the beginning of your programmer career, you must have done programs of 10, 15, 20 lines, maybe even 30, being pretty pessimistic. But this is just because you have done simple tasks, when a project grows it also increases the number of lines to implement it. Imagine now that you are implementing the World of Warcraft game, which is over 30GB in size: do you intend to put all the programming in a single file? This will be almost impossible to maintain later. That's where the module comes in.

A module will be a simple way to break your code into smaller pieces, like a file with some generic functions, or even a certain set of classes that you decide to use.

Your first module

A module has its filename without the extension  .py, so we will create the module  fibonacci. In the file  fibonacci.py insert the following code:

# escreve na tela todos os números da série de Fibonacci até n 
def fib(n): 
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a+b
    print() 

# retorna uma lista com os números da série de Fibonacci até o n
def fib2(n):
    result = []
    a, b = 0, 1
    while a < n:
        result.append(a)
        a, b = b, a+b
    return result

Save the file and open Python in the terminal:

$ python3

Now you will import the file into the terminal and run it with the value you want:

>>> import fibonacci 
>>> fibonacci.fib(10) 
0 1 1 2 3 5 8 
>>> fibonacci.fib2(10) 
[0, 1, 1, 2, 3, 5, 8] 
>>> fibonacci.__name__ 'fibonacci'

You can also name the modules you import, or import just one function from a module:

>>> from fibonacci import fib
>>> import numpy as np 
>>> from fibonacci import fib2 as fibonacci 
>>> 
>>> fib(10) 
0 1 1 2 3 5 8 
>>> fibonacci(10) 
[0, 1, 1, 2, 3, 5, 8]

Making a module executable

You can also add an executable snippet to the module (but which won't run in case of ) by inserting a behavior if it runs as  main. Add this to the end of our fibonacci module:

if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))

O  __main__ is the name given to the program when it runs. If you run the file  fibonacci.py, for example, its name during execution will be  __main__, while all others will be given their respective names.

With this piece of code you can run the program directly as if you didn't use that if, calling the function  fib using a parameter passed as an argument, but it won't be executed if you import it into a program:

$ python3 fibo.py 50
0 1 1 2 3 5 8 13 21 34

Pre-compiled modules

Python modules are precompiled to increase their speed when imported. They will be stored in directories called  __pycache__, with the name  modulo.versao.pyc. For example, in Python 3.3, the compiled version of  spam.py will be saved as  __pycache__/spam.cpython-33.pyc. This convention is used to allow different versions of the same module to be saved in the same folder, compiled for different versions of Python.

Python checks the file's compilation date from time to time to see if they need to be recompiled. As in Java, the file generated by the compilation works in the same way as a bytecode, and is completely independent of the platform, making it possible for the same compiled module to work correctly regardless of platform and architecture.

If you like, you can read more about modules in  the Python documentation .

You can also study  Caelum's Python workbook .

But what then? What do you think? Are there any questions left? Leave your opinion there in the comments.

How do you rate this article?

3



Lingy
Lingy

My personal blog about technology

Publish0x

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.