Last active
October 18, 2024 06:58
-
-
Save avalanchy/2a6aa364b12f9bca5e117b836132682c to your computer and use it in GitHub Desktop.
python cast function output to specifc type. most commonly decorate generator to return a list.
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
def as_list(func: Callable[..., Iterator[T]]) -> Callable[..., list[T]]: | |
"""Decorator that casts the output of the function to a list. | |
Example: | |
>>> @as_list | |
... def foo(): | |
... yield 123 | |
... | |
>>> foo() | |
[123] | |
""" | |
@functools.wraps(func) | |
def as_list_wrapper(*args, **kwargs): | |
ret = func(*args, **kwargs) | |
return list(ret) | |
return as_list_wrapper |
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
import functools | |
def cast_to(cast_func): | |
"""Cast function's output to a specified type. | |
Example: | |
>>> @cast_to(list) | |
... def foo(): | |
... yield 123 | |
... | |
>>> foo() | |
[123] | |
""" | |
def decorator_cast_to(func): | |
@functools.wraps(func) | |
def wrapper_cast_to(*args, **kwargs): | |
ret = func(*args, **kwargs) | |
return cast_func(ret) | |
return wrapper_cast_to | |
return decorator_cast_to |
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
In [7]: def a(): | |
l = [] | |
for i in range(10000): | |
l.append("a{}".format(i)) | |
return l | |
...: | |
In [8]: @cast_to(list) | |
def b(): | |
for i in range(10000): | |
yield "a{}".format(i) | |
...: | |
In [9]: %timeit a() | |
1.8 ms ± 25.9 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each) | |
In [10]: %timeit b() | |
1.98 ms ± 16.6 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment