Skip to content

    Chapter 25, Basic

    Modules and import

    A module is a `.py` file. A package is a folder of modules. This is how Python organizes its own and third-party code.

    Code for this chapter: basico/cap25_modulos.py

    Ways to import

    basico/cap25_modulos.pylinhas 10 a 16
    import math
    from math import sqrt, pi
    import datetime as dt
    
    print(math.sqrt(16), sqrt(25))
    print(f"{pi:.4f}")
    print(math.floor(2.7), math.ceil(2.1), math.gcd(12, 18))
    
    Output
    4.0 5.0
    3.1416
    2 3 6
    

    I prefer import modulo and use modulo.funcao, because the reader sees where each name comes from. Avoid from modulo import *: it throws dozens of names into your code and makes it impossible to know where each one came from.

    The standard library

    Python comes with a huge standard library, and knowing it prevents installing a package for what already exists:

    basico/cap25_modulos.pylinhas 21 a 29
    import statistics
    from datetime import date, timedelta
    
    notas = [7, 8, 9, 10]
    print(statistics.mean(notas), statistics.median(notas))
    hoje = date(2026, 10, 6)
    print(hoje.strftime("%d/%m/%Y"))
    print(hoje + timedelta(days=30))
    print((date(2026, 12, 25) - hoje).days)
    
    Output
    8.5 8.5
    06/10/2026
    2026-11-05
    80
    
    basico/cap25_modulos.pylinhas 31 a 34
    import random
    
    print(random.randint(1, 6) in range(1, 7))
    print(random.choice(["a", "b", "c"]) in "abc")
    
    Output
    True
    True
    

    The random is used for games and simulations. For passwords and tokens, which need to be truly unpredictable, use the module secrets.

    Your own modules

    Any file .py becomes an importable module. See a couple of files in the folder exemplos/modulos:

    exemplos/modulos/util.py
    """Funções de apoio importadas pelo programa principal."""
    
    
    def saudacao(nome: str) -> str:
        return f"Olá, {nome}!"
    
    
    if __name__ == "__main__":
        print(saudacao("teste do módulo"))
    
    exemplos/modulos/principal.py
    from util import saudacao
    
    print(saudacao("Ana"))
    
    Terminal
    python3 exemplos/modulos/principal.py
    

    When executing a script, Python places the script's folder at the beginning of the module search list, and that’s why from util import saudacao works.

    The if __name__ == "__main__" pattern

    Every module has a variable __name__. When the file is executed as a program, the value is "__main__". When it is imported, the value is the module's name. This test allows the same file to be both a library and a program at the same time:

    basico/cap25_modulos.pylinhas 39 a 44
    def main():
        print(f"executando com __name__ = {__name__!r}")
    
    
    if __name__ == "__main__":
        main()
    
    Output
    executando com __name__ = '__main__'
    

    Without this protection, importing the module would execute the entire program as a side effect.

    How Python finds modules

    The interpreter looks in sys.path, a list of folders, in order. After being imported, the module is stored in sys.modules, and the second import simply reuses what is already there:

    basico/cap25_modulos.pylinhas 49 a 51
    import sys
    
    print(type(sys.path).__name__, "math" in sys.modules)
    
    Output
    list True
    

    Third-party packages come from PyPI and are installed within a virtual environment (chapter 4), with pip install, uv add or poetry add. The own packages, with __init__.py and folder structure, return in the packaging chapter.

    Exercise 1

    Days between two dates

    Write dias_entre(inicio, fim) that receives dates in the format "2026-01-01" and return the number of days between them. Hint: date.fromisoformat.