Python の 型ガードパターン

レベル 5508 打鍵

TypeGuardを使って型を絞り込む関数を作成し、ユニオン型をより安全に扱います。

Python のコード

# 型ヒント用にTypeGuard(Python 3.10以降)とUnionをインポートします
1from typing import TypeGuard, Union
2
# 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

Python のレベル 5 のほかのコード例

← Python タイピング練習のトップへ