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
# 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, evitaWhere Python looks for modules
Python looks for modules in sys.path, which includes:
- the directory of the running script,
- the directories in
PYTHONPATH, - the installed libraries (
site-packages).
import sys
sys.path # lista di directoryCreating a module
Create mio_modulo.py:
# mio_modulo.py
PI = 3.14159
def area_cerchio(r):
return PI * r * rFrom another file in the same directory:
import mio_modulo
mio_modulo.area_cerchio(5) # 78.53975
from mio_modulo import area_cerchio, PIif __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.
# 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:
mio_pkg/
__init__.py
utenti.py
pagamenti.py
from mio_pkg import utenti
from mio_pkg.utenti import crea_utenteYour turn
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`.
Show hint
from math import sqrt
Solution available after 3 attempts
Review exercise
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).
Show hint
import random as rnd
Solution available after 3 attempts
Additional challenge
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.
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