從 Python 3.5 有什麼新特性? - Python @徐釀泉 的回答中得知,Python 3.5 中將會增加一個類型檢查的新功能(PEP 0484 -- Type Hints)。於是滿懷期待的等到昨天新版本一出便立即下載來嘗鮮,然而卻發現功能的實現和原來預想中的並不一樣。就像在stackoverflow(How / why does Python type hinting syntax work?)中提問者的描述一樣,在示例中
def greeting(name: str) -&> str:
return "Hello " + name
print(greeting("Martin"))
print(greeting(1))
運行結果:
Hello Martin
Traceback (most recent call last):
File "test.py", line 5, in &
print(greeting(1))
File "test.py", line 2, in greeting
return "Hello " + name
TypeError: Can"t convert "int" object to str implicitly
然後我又看到其實Python相關語法已經在Python 3.0 PEP 3107 -- Function Annotations 中已經實現,這一次 PEP 0484 -- Type Hints 只是新提供了一個 26.1. typing 來方便做各種類型檢查。比如TypeVar Union Dict 什麼的。
所以我猜想,難道Python 放出這個新功能是為了方便實現一個類型檢查的裝飾器嗎?
於是我自己又寫下如下代碼做驗證:
然而讓人有點失望的是,PEP 0484 -- Type Hints 似乎並沒有起到什麼新的作用,用以前的反射庫 inspect就好了,而且新庫typing會報讓人有點莫名奇妙的錯誤。
Traceback (most recent call last):
File "test_typehit.py", line 30, in &
print(type(inproduct([(5,2),(3,4)])))
File "test_typehit.py", line 20, in _typecheck
print(isinstance(ret,func_arg_annotations["return"]))
File "typing.py", line 423, in __instancecheck__
TypeError: Type variables cannot be used with isinstance().