Q&A
VSCode + Pylance で型チェックを初めて導入して勉強中の者です。
下記のコードで、Pylanceの型チェックでエラーが出る理由が分かりません。
python
1def int_func(arg: int): 2 print(arg) 3 4def hoge(arg: str | int): 5 if type(arg) is str: 6 return 7 int_func(arg) # ここでエラー
エラー内容
Argument of type "str | int" cannot be assigned to parameter "arg" of type "int" in function "int_func" Type "str | int" cannot be assigned to type "int" "str" is incompatible with "int"
hoge()
の中では引数が str
でないことを確認しているので int
しかありえないはず。
一方で、下記のコードだといずれもエラーは出ません。
python
1def fuga(arg: str | int): 2 if type(arg) is int: 3 int_func(arg) 4 5def piyo(arg: str | int): 6 if isinstance(arg, str): 7 return 8 int_func(arg)
知りたいこと
type()
とisinstance()
の違いがなぜ上記の型チェックに影響するのか(hoge()
とpiyo()
)- 同じ
type()
を使っても、なぜfuga()
だとOKなのにhoge()
だとダメなのか
回答1件
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。