Type hints

Programmazione a oggetti intermedia in Python

Jake Roach

Data Engineer

Codice senza type hints

class Student:
    def __init__(self, name, student_id, tuition_balance):
        self.name = name
        self.student_id = student_id
        self.tuition_balance = tuition_balance

# Trying to create a class can be tricky
walker = Student("Sarah Walker", 319921, 15000)
  • student_id dovrebbe essere un intero?
  • tuition_balance deve essere float o intero? Magari una stringa?
  • Dopo aver creato walker, come ricordare il suo tipo più avanti nel codice?
Programmazione a oggetti intermedia in Python

Type hints

Strumento opzionale per aggiungere al codice info sul tipo di un oggetto

  • Lettura e debug più semplici
  • Uno dei modi migliori per mostrare competenze Python di livello enterprise
  • Non imposto dall'interprete
  • Parole chiave dei tipi built-in, libreria typing, classi personalizzate
# Aggiungi un type hint quando crei
# una variabile
gpa: float = 3.92
# Aggiungi type hint alla definizione
# di una funzione/metodo
def check_grades(year: str) -> List[int]:
    ...
# Puoi usare anche classi personalizzate
students: Dict[str, Student] = {...}
Programmazione a oggetti intermedia in Python

Type hinting con tipi built-in

# Type hinting per logica dichiarativa
name: str = "Frost"  # Prima: name = "Frost"
student_id: int = 91031367
tuition_balance: float = 17452.78
# Type hinting per definizioni di funzioni/metodi
def get_schedule(semester: str) -> dict:
    ...
  • Usa la sintassi variabile: tipo
  • Dichiarativo, firma di funzione/metodo
  • def .... () -> tipo: per indicare il tipo di ritorno
Programmazione a oggetti intermedia in Python

Libreria typing

typing è una libreria che offre più strumenti per i type hint

  • List, Dict, Tuple
  • Suggerisci il tipo dell'oggetto e degli elementi
from typing import List, Dict

student_names: List[str] = ["Morgan", "Chuck", "Anna"]
student_gpas: Dict[str, float] = {
    "Casey": 3.71,
    "Sarah": 4.0
}
  • Any, Set, Iterator, Callable
Programmazione a oggetti intermedia in Python

Type hinting con classi personalizzate

class Student:
    def __init__(self, name: str, student_id: int, tuition_balance: float) -> None:
        self.name: str = name
        self.student_id: int = student_id
        self.tuition_balance: float = tuition_balance

    def get_course(self, course_id: str) -> Course:
        ...
        return course
# Usa Student e Course nei type hint
walker: Student = Student("Sarah Walker", 319921, 15000)
data_science: Course = walker.get_course("TDM-20100")
Programmazione a oggetti intermedia in Python

Verificare i tipi degli oggetti

# walker: Student = Student("Sarah Walker", 319921, 15000)
print(type(walker))
<class '__main__.Student'>
# data_science: Course = walker.get_course("TDM-20100")
print(type(data_science))
<class '__main__.Course'>
Programmazione a oggetti intermedia in Python

Esercitiamoci!

Programmazione a oggetti intermedia in Python

Preparing Video For Download...