File: _any_iterator.py

package info (click to toggle)
python-stripe 12.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 12,864 kB
  • sloc: python: 157,573; makefile: 13; sh: 9
file content (34 lines) | stat: -rw-r--r-- 1,053 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from typing import TypeVar, Iterator, AsyncIterator

T = TypeVar("T")


class AnyIterator(Iterator[T], AsyncIterator[T]):
    """
    AnyIterator supports iteration through both `for ... in <AnyIterator>` and `async for ... in <AnyIterator> syntaxes.
    """

    def __init__(
        self, iterator: Iterator[T], async_iterator: AsyncIterator[T]
    ) -> None:
        self._iterator = iterator
        self._async_iterator = async_iterator

        self._sync_iterated = False
        self._async_iterated = False

    def __next__(self) -> T:
        if self._async_iterated:
            raise RuntimeError(
                "AnyIterator error: cannot mix sync and async iteration"
            )
        self._sync_iterated = True
        return self._iterator.__next__()

    async def __anext__(self) -> T:
        if self._sync_iterated:
            raise RuntimeError(
                "AnyIterator error: cannot mix sync and async iteration"
            )
        self._async_iterated = True
        return await self._async_iterator.__anext__()