Pattern Type Guard in Python

Livello 5508 battiture

Questo usa TypeGuard per creare funzioni di restringimento del tipo per una gestione più sicura delle union.

Codice Python

# Importa TypeGuard (Python 3.10+) e Union per le annotazioni di tipo
1from typing import TypeGuard, Union
2
# class Cat definisce un gatto con metodo meow
3class Cat:
# meow restituisce il suono del gatto
4 def meow(self) -> str:
5 return "Meow!"
6
# class Dog definisce un cane con metodo bark
7class Dog:
# bark restituisce il suono del cane
8 def bark(self) -> str:
9 return "Woof!"
10
# is_cat è una funzione type guard per Cat
11def is_cat(animal: Union[Cat, Dog]) -> TypeGuard[Cat]:
# Restituisce True se animal è Cat, restringe il tipo
12 return isinstance(animal, Cat)
13
# is_dog è una funzione type guard per Dog
14def is_dog(animal: Union[Cat, Dog]) -> TypeGuard[Dog]:
# Restituisce True se animal è Dog, restringe il tipo
15 return isinstance(animal, Dog)
16
# make_sound usa type guard per chiamate sicure di metodi
17def make_sound(animal: Union[Cat, Dog]) -> str:
# Dopo is_cat, il type checker sa che animal è Cat
18 if is_cat(animal):
# Si può chiamare meow() in sicurezza
19 return animal.meow()
# Dopo is_dog, il type checker sa che animal è Dog
20 elif is_dog(animal):
# Si può chiamare bark() in sicurezza
21 return animal.bark()
# Fallback per tipi sconosciuti
22 return "Unknown"
23
# Test con istanza di Cat
24print(make_sound(Cat()))
# Test con istanza di Dog
25print(make_sound(Dog()))

Output

Meow!
Woof!
Esercitati a digitare questo codice

Esercitati a digitare questo codice. I risultati non vengono registrati in classifica.

Simboli in questo codice

I simboli che digiti in questo codice Python e quante volte compaiono.

  • (× 17
  • )× 17
  • :× 12
  • _× 7
  • ,× 6
  • "× 6
  • -× 5
  • [× 5
  • ]× 5
  • >× 5

Altri esempi Python di livello 5

← Pratica di digitazione Python