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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
|
"""Core objects for stream operators."""
from __future__ import annotations
import inspect
import functools
import sys
import warnings
from .aiter_utils import AsyncIteratorContext, aiter, assert_async_iterable
from typing import (
Any,
AsyncIterator,
Callable,
Generator,
Iterator,
Protocol,
Union,
TypeVar,
cast,
AsyncIterable,
Awaitable,
)
from typing_extensions import ParamSpec, Concatenate
__all__ = ["Stream", "Streamer", "StreamEmpty", "operator", "streamcontext"]
# Exception
class StreamEmpty(Exception):
"""Exception raised when awaiting an empty stream."""
pass
# Helpers
T = TypeVar("T")
X = TypeVar("X")
A = TypeVar("A", contravariant=True)
P = ParamSpec("P")
Q = ParamSpec("Q")
# Hack for python 3.8 compatibility
if sys.version_info < (3, 9):
P = TypeVar("P")
async def wait_stream(aiterable: BaseStream[T]) -> T:
"""Wait for an asynchronous iterable to finish and return the last item.
The iterable is executed within a safe stream context.
A StreamEmpty exception is raised if the sequence is empty.
"""
class Unassigned:
pass
last_item: Unassigned | T = Unassigned()
async with streamcontext(aiterable) as streamer:
async for item in streamer:
last_item = item
if isinstance(last_item, Unassigned):
raise StreamEmpty()
return last_item
# Core objects
class BaseStream(AsyncIterable[T], Awaitable[T]):
"""
Base class for streams.
See `Stream` and `Streamer` for more information.
"""
def __init__(self, factory: Callable[[], AsyncIterable[T]]) -> None:
"""Initialize the stream with an asynchronous iterable factory.
The factory is a callable and takes no argument.
The factory return value is an asynchronous iterable.
"""
aiter = factory()
assert_async_iterable(aiter)
self._generator = self._make_generator(aiter, factory)
def _make_generator(
self, first: AsyncIterable[T], factory: Callable[[], AsyncIterable[T]]
) -> Iterator[AsyncIterable[T]]:
"""Generate asynchronous iterables when required.
The first iterable is created beforehand for extra checking.
"""
yield first
del first
while True:
yield factory()
def __await__(self) -> Generator[Any, None, T]:
"""Await protocol.
Safely iterate and return the last element.
"""
return wait_stream(self).__await__()
def __or__(self, func: Callable[[BaseStream[T]], X]) -> X:
"""Pipe protocol.
Allow to pipe stream operators.
"""
return func(self)
def __add__(self, value: AsyncIterable[X]) -> Stream[Union[X, T]]:
"""Addition protocol.
Concatenate with a given asynchronous sequence.
"""
from .stream import chain
return chain(self, value)
def __getitem__(self, value: Union[int, slice]) -> Stream[T]:
"""Get item protocol.
Accept index or slice to extract the corresponding item(s)
"""
from .stream import getitem
return getitem(self, value)
# Disable sync iteration
# This is necessary because __getitem__ is defined
# which is a valid fallback for for-loops in python
__iter__: None = None
class Stream(BaseStream[T]):
"""Enhanced asynchronous iterable.
It provides the following features:
- **Operator pipe-lining** - using pipe symbol ``|``
- **Repeatability** - every iteration creates a different iterator
- **Safe iteration context** - using ``async with`` and the ``stream``
method
- **Simplified execution** - get the last element from a stream using
``await``
- **Slicing and indexing** - using square brackets ``[]``
- **Concatenation** - using addition symbol ``+``
It is not meant to be instanciated directly.
Use the stream operators instead.
Example::
xs = stream.count() # xs is a stream object
ys = xs | pipe.skip(5) # pipe xs and skip the first 5 elements
zs = ys[5:10:2] # slice ys using start, stop and step
async with zs.stream() as streamer: # stream zs in a safe context
async for z in streamer: # iterate the zs streamer
print(z) # Prints 10, 12, 14
result = await zs # await zs and return its last element
print(result) # Prints 14
result = await zs # zs can be used several times
print(result) # Prints 14
"""
def stream(self) -> Streamer[T]:
"""Return a streamer context for safe iteration.
Example::
xs = stream.count()
async with xs.stream() as streamer:
async for item in streamer:
<block>
"""
return self.__aiter__()
def __aiter__(self) -> Streamer[T]:
"""Asynchronous iteration protocol.
Return a streamer context for safe iteration.
"""
return streamcontext(next(self._generator))
# Advertise the proper synthax for entering a stream context
__aexit__: None = None
async def __aenter__(self) -> None:
raise TypeError(
"A stream object cannot be used as a context manager. "
"Use the `stream` method instead: "
"`async with xs.stream() as streamer`"
)
class Streamer(AsyncIteratorContext[T], BaseStream[T]):
"""Enhanced asynchronous iterator context.
It is similar to AsyncIteratorContext but provides the stream
magic methods for concatenation, indexing and awaiting.
It's not meant to be instanciated directly, use streamcontext instead.
Example::
ait = some_asynchronous_iterable()
async with streamcontext(ait) as streamer:
async for item in streamer:
await streamer[5]
"""
pass
def streamcontext(aiterable: AsyncIterable[T]) -> Streamer[T]:
"""Return a stream context manager from an asynchronous iterable.
The context management makes sure the aclose asynchronous method
of the corresponding iterator has run before it exits. It also issues
warnings and RuntimeError if it is used incorrectly.
It is safe to use with any asynchronous iterable and prevent
asynchronous iterator context to be wrapped twice.
Correct usage::
ait = some_asynchronous_iterable()
async with streamcontext(ait) as streamer:
async for item in streamer:
<block>
For streams objects, it is possible to use the stream method instead::
xs = stream.count()
async with xs.stream() as streamer:
async for item in streamer:
<block>
"""
aiterator = aiter(aiterable)
if isinstance(aiterator, Streamer):
return aiterator
return Streamer(aiterator)
# Operator type protocol
class OperatorType(Protocol[P, T]):
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> Stream[T]:
...
def raw(self, *args: P.args, **kwargs: P.kwargs) -> AsyncIterator[T]:
...
class PipableOperatorType(Protocol[A, P, T]):
def __call__(
self, source: AsyncIterable[A], /, *args: P.args, **kwargs: P.kwargs
) -> Stream[T]:
...
def raw(
self, source: AsyncIterable[A], /, *args: P.args, **kwargs: P.kwargs
) -> AsyncIterator[T]:
...
def pipe(
self, *args: P.args, **kwargs: P.kwargs
) -> Callable[[AsyncIterable[A]], Stream[T]]:
...
# Operator decorator
def operator(
func: Callable[P, AsyncIterator[T]] | None = None,
pipable: bool | None = None,
) -> OperatorType[P, T]:
"""Create a stream operator from an asynchronous generator
(or any function returning an asynchronous iterable).
Decorator usage::
@operator
async def random(offset=0., width=1.):
while True:
yield offset + width * random.random()
The return value is a dynamically created class.
It has the same name, module and doc as the original function.
A new stream is created by simply instanciating the operator::
xs = random()
The original function is called at instanciation to check that
signature match. Other methods are available:
- `original`: the original function as a static method
- `raw`: same as original but add extra checking
The `pipable` argument is deprecated, use `pipable_operator` instead.
"""
# Handle compatibility with legacy (aiostream <= 0.4)
if pipable is not None or func is None:
warnings.warn(
"The `pipable` argument is deprecated. Use either `@operator` or `@pipable_operator` directly.",
DeprecationWarning,
)
if func is None:
return pipable_operator if pipable else operator # type: ignore
if pipable is True:
return pipable_operator(func) # type: ignore
# First check for classmethod instance, to avoid more confusing errors later on
if isinstance(func, classmethod):
raise ValueError(
"An operator cannot be created from a class method, "
"since the decorated function becomes an operator class"
)
# Gather data
bases = (Stream,)
name = func.__name__
module = func.__module__
extra_doc = func.__doc__
doc = extra_doc or f"Regular {name} stream operator."
# Extract signature
signature = inspect.signature(func)
parameters = list(signature.parameters.values())
if parameters and parameters[0].name in ("self", "cls"):
raise ValueError(
"An operator cannot be created from a method, "
"since the decorated function becomes an operator class"
)
# Look for "more_sources"
for i, p in enumerate(parameters):
if p.name == "more_sources" and p.kind == inspect.Parameter.VAR_POSITIONAL:
more_sources_index = i
break
else:
more_sources_index = None
# Injected parameters
self_parameter = inspect.Parameter("self", inspect.Parameter.POSITIONAL_OR_KEYWORD)
inspect.Parameter("cls", inspect.Parameter.POSITIONAL_OR_KEYWORD)
# Wrapped static method
original = func
original.__qualname__ = name + ".original"
# Raw static method
raw = func
raw.__qualname__ = name + ".raw"
# Init method
def init(self: BaseStream[T], *args: P.args, **kwargs: P.kwargs) -> None:
if more_sources_index is not None:
for source in args[more_sources_index:]:
assert_async_iterable(source)
factory = functools.partial(raw, *args, **kwargs)
return BaseStream.__init__(self, factory)
# Customize init signature
new_parameters = [self_parameter] + parameters
init.__signature__ = signature.replace(parameters=new_parameters) # type: ignore[attr-defined]
# Customize init method
init.__qualname__ = name + ".__init__"
init.__name__ = "__init__"
init.__module__ = module
init.__doc__ = f"Initialize the {name} stream."
# Gather attributes
attrs = {
"__init__": init,
"__module__": module,
"__doc__": doc,
"raw": staticmethod(raw),
"original": staticmethod(original),
}
# Create operator class
return cast("OperatorType[P, T]", type(name, bases, attrs))
def pipable_operator(
func: Callable[Concatenate[AsyncIterable[X], P], AsyncIterator[T]],
) -> PipableOperatorType[X, P, T]:
"""Create a pipable stream operator from an asynchronous generator
(or any function returning an asynchronous iterable).
Decorator usage::
@pipable_operator
async def multiply(source, factor):
async with streamcontext(source) as streamer:
async for item in streamer:
yield factor * item
The first argument is expected to be the asynchronous iteratable used
for piping.
The return value is a dynamically created class.
It has the same name, module and doc as the original function.
A new stream is created by simply instanciating the operator::
xs = random()
ys = multiply(xs, 2)
The original function is called at instanciation to check that
signature match. The source is also checked for asynchronous iteration.
The operator also have a pipe class method that can be used along
with the piping synthax::
xs = random()
ys = xs | multiply.pipe(2)
This is strictly equivalent to the previous example.
Other methods are available:
- `original`: the original function as a static method
- `raw`: same as original but add extra checking
The raw method is useful to create new operators from existing ones::
@pipable_operator
def double(source):
return multiply.raw(source, 2)
"""
# First check for classmethod instance, to avoid more confusing errors later on
if isinstance(func, classmethod):
raise ValueError(
"An operator cannot be created from a class method, "
"since the decorated function becomes an operator class"
)
# Gather data
bases = (Stream,)
name = func.__name__
module = func.__module__
extra_doc = func.__doc__
doc = extra_doc or f"Regular {name} stream operator."
# Extract signature
signature = inspect.signature(func)
parameters = list(signature.parameters.values())
if parameters and parameters[0].name in ("self", "cls"):
raise ValueError(
"An operator cannot be created from a method, "
"since the decorated function becomes an operator class"
)
# Look for "more_sources"
for i, p in enumerate(parameters):
if p.name == "more_sources" and p.kind == inspect.Parameter.VAR_POSITIONAL:
more_sources_index = i
break
else:
more_sources_index = None
# Injected parameters
self_parameter = inspect.Parameter("self", inspect.Parameter.POSITIONAL_OR_KEYWORD)
cls_parameter = inspect.Parameter("cls", inspect.Parameter.POSITIONAL_OR_KEYWORD)
# Wrapped static method
original = func
original.__qualname__ = name + ".original"
# Raw static method
def raw(
arg: AsyncIterable[X], *args: P.args, **kwargs: P.kwargs
) -> AsyncIterator[T]:
assert_async_iterable(arg)
if more_sources_index is not None:
for source in args[more_sources_index - 1 :]:
assert_async_iterable(source)
return func(arg, *args, **kwargs)
# Custonize raw method
raw.__signature__ = signature # type: ignore[attr-defined]
raw.__qualname__ = name + ".raw"
raw.__module__ = module
raw.__doc__ = doc
# Init method
def init(
self: BaseStream[T], arg: AsyncIterable[X], *args: P.args, **kwargs: P.kwargs
) -> None:
assert_async_iterable(arg)
if more_sources_index is not None:
for source in args[more_sources_index - 1 :]:
assert_async_iterable(source)
factory = functools.partial(raw, arg, *args, **kwargs)
return BaseStream.__init__(self, factory)
# Customize init signature
new_parameters = [self_parameter] + parameters
init.__signature__ = signature.replace(parameters=new_parameters) # type: ignore[attr-defined]
# Customize init method
init.__qualname__ = name + ".__init__"
init.__name__ = "__init__"
init.__module__ = module
init.__doc__ = f"Initialize the {name} stream."
# Pipe class method
def pipe(
cls: PipableOperatorType[X, P, T],
/,
*args: P.args,
**kwargs: P.kwargs,
) -> Callable[[AsyncIterable[X]], Stream[T]]:
return lambda source: cls(source, *args, **kwargs)
# Customize pipe signature
if parameters and parameters[0].kind in (
inspect.Parameter.POSITIONAL_ONLY,
inspect.Parameter.POSITIONAL_OR_KEYWORD,
):
new_parameters = [cls_parameter] + parameters[1:]
else:
new_parameters = [cls_parameter] + parameters
pipe.__signature__ = signature.replace(parameters=new_parameters) # type: ignore[attr-defined]
# Customize pipe method
pipe.__qualname__ = name + ".pipe"
pipe.__module__ = module
pipe.__doc__ = f'Pipable "{name}" stream operator.'
if extra_doc:
pipe.__doc__ += "\n\n " + extra_doc
# Gather attributes
attrs = {
"__init__": init,
"__module__": module,
"__doc__": doc,
"raw": staticmethod(raw),
"original": staticmethod(original),
"pipe": classmethod(pipe), # type: ignore[arg-type]
}
# Create operator class
return cast(
"PipableOperatorType[X, P, T]",
type(name, bases, attrs),
)
|