漸進的型付け
簡潔でとても良い説明
code:python
def foo(x: int):
y: str = x # NG
error: Incompatible types in assignment (expression has type "int", variable has type "str") [assignment]
暗黙のAnyを明示
code:python
import typing
def foo(x: typing.Any):
y: str = x # OK
code:python
def foo(x: int):
y: typing.Any = x # OK
Anyとobjectの違い
code:python
def foo(x: int):
y: object = x # OK
code: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がアップキャストもダウンキャストも暗黙に行える特殊な型ということ
返り値の型を推測したりしない
code:python
def foo(x: int):
return x
print(typing.reveal_type(foo))
note: Revealed type is "def (x: builtins.int) -> Any"
これはTypeScriptとは異なる挙動
https://gyazo.com/485b1234b2e40fa0839bf9379e8ddce3
code:python
def foo(x: int) -> int:
return x
print(typing.reveal_type(foo))
note: Revealed type is "def (x: builtins.int) -> builtins.int"
人間がこうやって明示することが期待されている
https://gyazo.com/9ea5aa1dec79c546747debfa28db2621