Last active
January 13, 2025 16:22
-
-
Save angstwad/eeb2a98cc255856ebbad325aa18bef29 to your computer and use it in GitHub Desktop.
enumerate with asyncio in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import AsyncIterable | |
async def enumerate_async[T](iterable: AsyncIterable[T], start=0) -> tuple[int, T]: | |
counter = start | |
async for item in iterable: | |
yield counter, item | |
counter += 1 | |
# example usage | |
import aiofiles | |
async with aiofiles.open('some_boring_file', 'r') as f: | |
async for i, line in enumerate_async(f): | |
do_something_with_index(i) | |
do_something_with_file(line) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Copyright 2024 Paul Durivage <[email protected]> | |
Licensed under the Apache License, Version 2.0 (the "License"); | |
you may not use this file except in compliance with the License. | |
You may obtain a copy of the License at | |
http://www.apache.org/licenses/LICENSE-2.0 | |
Unless required by applicable law or agreed to in writing, software | |
distributed under the License is distributed on an "AS IS" BASIS, | |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
See the License for the specific language governing permissions and | |
limitations under the License. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment