最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - What type hint should I use for an object that can be iterated through multiple times? - Stack Overflow

programmeradmin0浏览0评论

Sometimes I have a function that takes a parameter, and I need to be able to loop through that parameter multiple times. For example:

def loop_twice(param: MultiIterable):
    for thing in param:
        print(thing)

    for thing in param:
        print(f"{thing} again")

Importantly, I don't care about ordering (if I did, I would use Sequence). I just want to be able to iterate through the data twice. It could be a Set, a Tuple, a List, or any custom object that supports iter being called on it twice.

What's the best type-hint for such a parameter?

Using Iterable doesn't seem right because generators are iterable, but it's also allowed for them to only run once.

Sequence seems closer, but requires __getitem__ which I don't need. Collection currently seems like the best option, but I also don't need __contains__. How should I type-hint this?

发布评论

评论列表(0)

  1. 暂无评论