简体   繁体   English

Python类型提示-如何提示默认不为None的可选参数?

[英]Python type hinting - how to hint optional argument whose default is not None?

I am trying to implement PEP-484 in my Python 3 code for practice. 我正在尝试在我的Python 3代码中实现PEP-484。 While working on the following practice question, which looks like: 在处理以下练习问题时,它看起来像:

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

Is it possible to hint n in the function definition to be -- const str or int ? 是否可以在函数定义中提示nconst str or int If yes, how to do it? 如果是,该怎么办?

I read the cheat-sheet and currently I am using from typing import Optional and n: Optional[int] but its not working as desired. 我阅读了备忘单 ,当前正在通过from typing import Optionaln: Optional[int]它,但是它无法正常工作。

The Optional[X] is still only a type hint - it means X or None . Optional[X]仍然只是类型提示-它表示X or None Perhaps here you'd need an Union instead: 也许在这里您需要一个Union

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM