2017-04-07 69 views
4

我寫一個函數與左邊的說法,只是類似像內置range功能如何寫多個簽名提示在PyCharm與Python3

的問題是,如何編寫類型提示,可以顯示它應該被調用的兩種方式。

例如,當我在range功能PyCharm鍵入命令+ P(CTRL + P)(範圍是在PY3的對象,但它是沒有問題的):

self:range, stop: int 
------------------------------------------------- 
self:range, start: int, stop: int, step: int=-1 

type hints picture of range function

my_range

def my_range(start: int, stop: int = None, step: int=1): 
""" 
list_range(stop) 
list_range(start, stop, step) 

return list of integers from start (default 0) to stop, 
incrementing by step (default 1). 

""" 
if stop is None: 
    start, stop = 0, start 
return list(range(start, stop, step)) 

類型命令+ p後,我得到了:

start: int, stop: Optional[int], step: int=-1 

有誰知道如何實現?非常感謝您的幫助!

+1

也許嘗試尋找使用[重載](http://mypy.readthedocs.io/en/latest/function_overloading.html)? (函數重載是PEP 484的一部分,Pycharm正在理解/正在積極努力朝着遵從的方向發展。鏈接的文檔指出,mypy僅在存根中理解重載註釋,但是如果這是最新的/如果也是這種情況爲Pycharm)。 (如果你想查看'range'函數/對象具有的確切類型註釋,請參見[typeshed](https://github.com/python/typeshed/blob/master/stdlib/3/builtins.pyi#L717)) 。 – Michael0x2a

+0

它的工作原理!非常感謝! – Garfield

回答

0

嘗試typing模塊!與類型註釋有很多關聯,包括typing.Optional。像這樣使用它:

import typing 

def f(required_arg: int, optional_arg:typing.Optional[int]=None): 
    # ...