subscription
- utilitools.subscription(type=None, /)[source]
- Transforms a function into a subscription object.Subscription applies to objects that behave as sequences.
Attention
The object must accept precisely one positional argument if it is a function.
The object must not accept arguments at all if it is a generator.
- Parameters
type (collections.Callable) –
The returned data type when the key is slice.By default, returnedutilitools.islice
.- Returns
A subscription object that already implements the __getitem__ magic method.
- Return type
utilitools.utilities.Subscription
- Raises
TypeError –
If type is not a callable that accepts an iterator.
If the function does not accept one positional argument.
If the generator accepts at least one argument.
If the key is not int or slice.
Examples
from utilitools import subscription
@subscription(tuple)
def digital_sum(n):
return sum(map(int, str(n)))
@subscription(list)
def fibonacci():
a, b = 0, 1
yield a
while True:
a, b = b, a + b
yield a
Subscription from a function when the key is int:
>>> digital_sum[123]
6
Subscription from a generator when the key is int:
>>> fibonacci[123]
22698374052006863956975682
Subscription from a function when the key is slice while the type is a tuple:
>>> digital_sum[10:20:3]
(1, 4, 7, 10)
Subscription from a generator when the key is slice while the type is a list:
>>> fibonacci[10:20:3]
[55, 233, 987, 4181]