[Python] What type hint should I use for an object that can be iterated through multiple times?

Discussão em 'Python' iniciado por Stack, Março 14, 2025.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página