Gradual Typing 簡潔でとても良い説明
https://mypy-play.net/?mypy=latest&python=3.11 python
def foo(x: int):
y: str = x # NG
error: Incompatible types in assignment (expression has type "int", variable has type "str") [assignment]import typing
def foo(x: typing.Any):
y: str = x # OK
python
def foo(x: int):
y: typing.Any = x # OK
def foo(x: int):
y: object = x # OK
python
def foo(x: object):
y: str = x # NG
error: Incompatible types in assignment (expression has type "object", variable has type "str") [assignment]
Anyと違ってobjectは単なるトップ型なのでobject型の値をstr型の値に代入しようとする(暗黙のダウンキャスト)はNG
返り値の型を推測したりしない python
def foo(x: int):
return x
print(typing.reveal_type(foo))
note: Revealed type is "def (x: builtins.int) -> Any"def foo(x: int) -> int:
return x
print(typing.reveal_type(foo))
note: Revealed type is "def (x: builtins.int) -> builtins.int"