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

后端 未结 1 396
故里飘歌
故里飘歌 2021-02-13 00:51

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 inte
1条回答
  •  北荒
    北荒 (楼主)
    2021-02-13 01:19

    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.

    0 讨论(0)
提交回复
热议问题