Skip to content

Instantly share code, notes, and snippets.

@e3krisztian
Last active August 14, 2018 07:21
Show Gist options
  • Save e3krisztian/8daa5c24dc258ab64e963adb68b82f31 to your computer and use it in GitHub Desktop.
Save e3krisztian/8daa5c24dc258ab64e963adb68b82f31 to your computer and use it in GitHub Desktop.
Python @converter decorator
import functools
def converter(convert):
"""Decorator for making decorators converting function return values.
Take a single argument function and make it into a decorator
converting return values of other functions.
"""
@functools.wraps(convert)
def converter(f):
@functools.wraps(f)
def converted(*args, **kwargs):
return convert(f(*args, **kwargs))
return converted
return converter
# list is already defined, so as_list is best defined as
as_list1 = converter(list)
# test as_list1
@as_list1
def gen1():
for i in range(10):
yield i
assert gen1() == list(range(10))
# or have one more indirection just to test the decorator as decorator
@converter
def as_list2(items):
return list(items)
# test as_list2
@as_list2
def gen2():
for i in range(10):
yield i
assert gen2() == list(range(10))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment