简体   繁体   中英

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. 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 ? 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.

The Optional[X] is still only a type hint - it means X or None . Perhaps here you'd need an Union instead:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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