Typové anotace

Intermediate Object-Oriented Programming in Python

Jake Roach

Data Engineer

Kód bez typových anotací

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)
  • Je student_id celé číslo?
  • Má být tuition_balance float, celé číslo nebo řetězec?
  • Jak si zapamatujeme typ proměnné walker na jiném místě v kódu?
Intermediate Object-Oriented Programming in Python

Typové anotace

Volitelný nástroj pro přidání informací o typech do kódu

  • Zlepšuje čitelnost a ladění
  • Jeden z nejlepších způsobů, jak prokázat profesionální znalost Pythonu
  • Interpret ji nevynucuje
  • Vestavěné typy, knihovna typing, vlastní třídy
# Add type hinting when creating a 
# variable
gpa: float = 3.92
# Add type hinting to a function/method 
# definition
def check_grades(year: str) -> List[int]:
    ...
# Can even use custom classes
students: Dict[str, Student] = {...}
Intermediate Object-Oriented Programming in Python

Typové anotace s vestavěnými typy

# Type hinting for declarative logic
name: str = "Frost"  # Before: name = "Frost"
student_id: int = 91031367
tuition_balance: float = 17452.78
# Type hinting for function/method definitions
def get_schedule(semester: str) -> dict:
    ...
  • Syntaxe variable: type
  • Deklarativní styl, signatura funkce/metody
  • def .... () -> type: pro návratový typ
Intermediate Object-Oriented Programming in Python

Knihovna typing

typing je knihovna nabízející další nástroje pro typové anotace

  • List, Dict, Tuple
  • Anotace nadřazených objektů i jejich prvků
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
Intermediate Object-Oriented Programming in Python

Typové anotace s vlastními třídami

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
# Use Student and Course to type hint
walker: Student = Student("Sarah Walker", 319921, 15000)
data_science: Course = walker.get_course("TDM-20100")
Intermediate Object-Oriented Programming in Python

Ověření typů objektů

# 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'>
Intermediate Object-Oriented Programming in Python

Pojďme si to procvičit!

Intermediate Object-Oriented Programming in Python

Preparing Video For Download...