@@ -412,51 +412,52 @@ def ixor(a, b):
412412
413413# Asynchronous Iterator Operations ********************************************#
414414
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 ):
416420 """aiter(async_iterable) -> async_iterator
417421 aiter(async_callable, sentinel) -> async_iterator
418422
419- An async version of the iter() builtin.
423+ Like the iter() builtin but for async iterables and callables .
420424 """
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 :
426426 if not isinstance (obj , AsyncIterable ):
427427 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 ):
441446 """anext(async_iterator[, default])
442447
443448 Return the next item from the async iterator.
444449 If default is given and the iterator is exhausted,
445450 it is returned instead of raising StopAsyncIteration.
446451 """
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__
454455 try :
455456 return await anxt ()
456457 except StopAsyncIteration :
457- if lenargs == 1 :
458+ if default is _NOT_PROVIDED :
458459 raise
459- return args [ 1 ] # default
460+ return default
460461
461462
462463try :
0 commit comments