Skip to content

Instantly share code, notes, and snippets.

@avalanchy
Last active March 29, 2024 09:43
Show Gist options
  • Save avalanchy/2a6aa364b12f9bca5e117b836132682c to your computer and use it in GitHub Desktop.
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.
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
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