How can I create a type hint that my returned list contains strings?

僤鯓⒐⒋嵵緔 提交于 2020-01-22 13:23:19

问题


I want to use Type Hints in my Python program. How can I create Type Hints for complex data structures like

  • lists with strings
  • a generator returning integers?

Example

def names() -> list:
    # I would like to specify that the list contains strings?
    return ['Amelie', 'John', 'Carmen']

def numbers():
    # Which type should I specify for `numbers()`?
    for num in range(100):
        yield num    

回答1:


Use the typing module; it contains generics, type objects you can use to specify containers with constraints on their contents:

import typing

def names() -> typing.List[str]:  # list object with strings
    return ['Amelie', 'John', 'Carmen']

def numbers() -> typing.Iterator[int]:  # iterator yielding integers
    for num in range(100):
        yield num

Depending on how you design your code and how you want to use the return value of names(), you could also use the types.Sequence and types.MutableSequence types here, depending on wether or not you expect to be able to mutate the result.

A generator is a specific type of iterator, so typing.Iterator is appropriate here. If your generator also accepts send() values and uses return to set a StopIteration value, you can use the typing.Generator object too:

def filtered_numbers(filter) -> typing.Generator[int, int, float]:
    # contrived generator that filters numbers; returns percentage filtered.
    # first send a limit!
    matched = 0
    limit = yield
    yield  # one more yield to pause after sending
    for num in range(limit):
        if filter(num):
            yield num
            matched += 1
    return (matched / limit) * 100

If you are new to type hinting, then PEP 483 – The Theory of Type Hints may be helpful.



来源:https://stackoverflow.com/questions/37386499/how-can-i-create-a-type-hint-that-my-returned-list-contains-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!