Python の 型ガードパターン
レベル 5508 打鍵
TypeGuardを使って型を絞り込む関数を作成し、ユニオン型をより安全に扱います。
Python のコード
# 型ヒント用にTypeGuard(Python 3.10以降)とUnionをインポートします1from typing import TypeGuard, Union2 # Catはmeowメソッドを持つ猫のクラスです3class Cat: # meowは猫の鳴き声を返します4 def meow(self) -> str:5 return "Meow!"6 # Dogはbarkメソッドを持つ犬のクラスです7class Dog: # barkは犬の鳴き声を返します8 def bark(self) -> str:9 return "Woof!"10 # is_catはCat用の型ガード関数です11def is_cat(animal: Union[Cat, Dog]) -> TypeGuard[Cat]: # animalがCatならTrueを返し、型を絞り込みます12 return isinstance(animal, Cat)13 # is_dogはDog用の型ガード関数です14def is_dog(animal: Union[Cat, Dog]) -> TypeGuard[Dog]: # animalがDogならTrueを返し、型を絞り込みます15 return isinstance(animal, Dog)16 # make_soundは型ガードを使って安全にメソッドを呼び出します17def make_sound(animal: Union[Cat, Dog]) -> str: # is_catがTrueなら、型チェッカーはanimalをCatとして扱います18 if is_cat(animal): # Catのmeow()を安全に呼び出せます19 return animal.meow() # is_dogがTrueなら、型チェッカーはanimalをDogとして扱います20 elif is_dog(animal): # Dogのbark()を安全に呼び出せます21 return animal.bark() # どちらでもない場合のフォールバックです22 return "Unknown"23 # Catインスタンスでテストします24print(make_sound(Cat()))# Dogインスタンスでテストします25print(make_sound(Dog()))実行結果
Meow! Woof!
このコードでタイピング練習ができます。記録はランキングに反映されません。
このコードで使う記号
この Python のコードで打つ記号と、出てくる回数です。
(× 17)× 17:× 12_× 7,× 6"× 6-× 5[× 5]× 5>× 5