@@ -412,51 +412,52 @@ def ixor(a, b):
412
412
413
413
# Asynchronous Iterator Operations ********************************************#
414
414
415
- async def aiter (* args ):
415
+
416
+ _NOT_PROVIDED = object () # sentinel object to detect when a kwarg was not given
417
+
418
+
419
+ def aiter (obj , sentinel = _NOT_PROVIDED ):
416
420
"""aiter(async_iterable) -> async_iterator
417
421
aiter(async_callable, sentinel) -> async_iterator
418
422
419
- An async version of the iter() builtin.
423
+ Like the iter() builtin but for async iterables and callables .
420
424
"""
421
- lenargs = len (args )
422
- if lenargs != 1 and lenargs != 2 :
423
- raise TypeError (f'aiter expected 1 or 2 arguments, got { lenargs } ' )
424
- if lenargs == 1 :
425
- obj , = args
425
+ if sentinel is _NOT_PROVIDED :
426
426
if not isinstance (obj , AsyncIterable ):
427
427
raise TypeError (f'aiter expected an AsyncIterable, got { type (obj )} ' )
428
- async for i in obj .__aiter__ ():
429
- yield i
430
- return
431
- # lenargs == 2
432
- async_callable , sentinel = args
433
- while True :
434
- value = await async_callable ()
435
- if value == sentinel :
436
- break
437
- yield value
438
-
439
-
440
- async def anext (* args ):
428
+ if isinstance (obj , AsyncIterator ):
429
+ return obj
430
+ return (i async for i in obj )
431
+
432
+ if not callable (obj ):
433
+ raise TypeError (f'aiter expected an async callable, got { type (obj )} ' )
434
+
435
+ async def ait ():
436
+ while True :
437
+ value = await obj ()
438
+ if value == sentinel :
439
+ break
440
+ yield value
441
+
442
+ return ait ()
443
+
444
+
445
+ async def anext (async_iterator , default = _NOT_PROVIDED ):
441
446
"""anext(async_iterator[, default])
442
447
443
448
Return the next item from the async iterator.
444
449
If default is given and the iterator is exhausted,
445
450
it is returned instead of raising StopAsyncIteration.
446
451
"""
447
- lenargs = len (args )
448
- if lenargs != 1 and lenargs != 2 :
449
- raise TypeError (f'anext expected 1 or 2 arguments, got { lenargs } ' )
450
- ait = args [0 ]
451
- if not isinstance (ait , AsyncIterator ):
452
- raise TypeError (f'anext expected an AsyncIterable, got { type (ait )} ' )
453
- anxt = ait .__anext__
452
+ if not isinstance (async_iterator , AsyncIterator ):
453
+ raise TypeError (f'anext expected an AsyncIterator, got { type (async_iterator )} ' )
454
+ anxt = async_iterator .__anext__
454
455
try :
455
456
return await anxt ()
456
457
except StopAsyncIteration :
457
- if lenargs == 1 :
458
+ if default is _NOT_PROVIDED :
458
459
raise
459
- return args [ 1 ] # default
460
+ return default
460
461
461
462
462
463
try :
0 commit comments