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]
- 暗黙のAnyを明示 python
import typing
def foo(x: typing.Any):
y: str = x # OK
python
def foo(x: int):
y: typing.Any = x # OK
- Anyとobjectの違い python
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
- これが普通の型の振る舞い
- Anyがアップキャストもダウンキャストも暗黙に行える特殊な型ということ
-
返り値の型を推測したりしない python
def foo(x: int):
return x
print(typing.reveal_type(foo))
note: Revealed type is "def (x: builtins.int) -> Any"
- これはTypeScriptとは異なる挙動
- python
def foo(x: int) -> int:
return x
print(typing.reveal_type(foo))
note: Revealed type is "def (x: builtins.int) -> builtins.int"
- 人間がこうやって明示することが期待されている