Skip to main content
eLearner.app
Module 7 · Lesson 4 of 428/36 in the course~10 min
Module lessons (4/4)

import and modules

A module in Python is simply a .py file. To use the code of a module from another file, you import it.

Forms of import

Python
# 1) import del modulo intero
import math
math.sqrt(16)        # 4.0
math.pi              # 3.14159...

# 2) import di nomi specifici
from math import sqrt, pi
sqrt(16)             # ora direttamente disponibile
pi

# 3) import con alias
import numpy as np      # convenzione idiomatica
from datetime import datetime as dt

# 4) import "star" (sconsigliato)
from math import *      # inquina il namespace, evita

Where Python looks for modules

Python looks for modules in sys.path, which includes:

  1. the directory of the running script,
  2. the directories in PYTHONPATH,
  3. the installed libraries (site-packages).
Python
import sys
sys.path     # lista di directory

Creating a module

Create mio_modulo.py:

Python
# mio_modulo.py
PI = 3.14159

def area_cerchio(r):
    return PI * r * r

From another file in the same directory:

Python
import mio_modulo
mio_modulo.area_cerchio(5)   # 78.53975

from mio_modulo import area_cerchio, PI

if __name__ == "__main__":

When a script is executed directly, its special variable __name__ equals "__main__". When the same file is imported as a module, __name__ equals the module name.

Python
# strumento.py

def fai_qualcosa():
    print("lavoro!")

if __name__ == "__main__":
    # eseguito solo se lanci `python strumento.py`
    # NON viene eseguito se qualcuno importa questo file
    fai_qualcosa()

This is the standard pattern for files that can serve as both a reusable module and an executable script.

Packages: folders of modules

A directory containing an __init__.py file (even an empty one) becomes an importable package:

Code
mio_pkg/
    __init__.py
    utenti.py
    pagamenti.py
Python
from mio_pkg import utenti
from mio_pkg.utenti import crea_utente

Your turn

Exercise#python.m7.l4.e1
Attempts: 0Loading…

Import the function `sqrt` from the `math` module (with `from math import sqrt`), then compute the square root of 144 and assign it to `r`. Evaluate `r`.

Loading editor…
Show hint

from math import sqrt

Solution available after 3 attempts

Review exercise

Exercise#python.m7.l4.e2
Attempts: 0Loading…

Import the `random` module with alias `rnd` (`import random as rnd`), then set the seed to 42 with rnd.seed(42), and evaluate rnd.randint(1, 100).

Loading editor…
Show hint

import random as rnd

Solution available after 3 attempts

Additional challenge

Exercise#python.m7.l4.e3
Attempts: 0Loading…

Import the `sin` and `cos` functions directly from the `math` module using `from ... import ...`. Calculate the sum of `sin(0)` and `cos(0)`, store it in `trig_sum`, and evaluate it.

Loading editor…
Show hint

sin(0) yields 0.0, cos(0) yields 1.0. The sum is 1.0. Use from math import sin, cos.

Solution available after 3 attempts