2017-07-17 50 views
0

我正在嘗試在我的Python 3代碼中實現PEP-484。而在下面的練習問題,它看起來像工作:Python類型提示 - 如何提示可選參數的默認值不是None?

def fetch_n(what: str, n="all") -> List[obj]: 
    query = "some sql string" 
    if n == "all": 
     # do the fetching 
    elif isinstance(n, int): 
     query = query + " LIMIT ?" 
     # do the fetching 
    else: 
     raise ValueError 

是否有可能暗示n在函數定義是 - const str or int?如果是的話,該怎麼做?

我讀了cheat-sheet,目前我使用的是from typing import Optionaln: Optional[int],但它不能按照需要工作。

回答

2

Optional[X]仍然只是一種類型的提示 - 它意味着X or None。也許在這裏你需要一個Union來代替:

def fetch_n(what: str, n: Union[str, int] = "all") -> List[obj]: 
    ... 
+0

聯盟在這裏是正確的。 +1 –

相關問題