Last active
May 15, 2019 19:37
-
-
Save jmborr/da3a0ec8f192c662115f2e35dc24304e to your computer and use it in GitHub Desktop.
decorator to transform the return type of a function from dictionary to namedtuple
This file contains 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 namedtuplefy(func): | |
r""" | |
Decorator to transform the return dictionary of a function into | |
a namedtuple | |
Parameters | |
---------- | |
func: Function | |
Function to be decorated | |
name: str | |
Class name for the namedtuple. If None, the name of the function | |
will be used | |
Returns | |
------- | |
Function | |
""" | |
@functools.wraps(func) | |
def wrapper(*args, **kwargs): | |
res = func(*args, **kwargs) | |
if wrapper.nt is None: | |
if isinstance(res, Mapping) is False: | |
raise ValueError('Cannot namedtuplefy a non-dict') | |
wrapper.nt = namedtuple(func.__name__ + '_nt', res.keys()) | |
return wrapper.nt(**res) | |
wrapper.nt = None | |
return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment