Skip to content

Instantly share code, notes, and snippets.

@jmborr
Last active May 15, 2019 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmborr/da3a0ec8f192c662115f2e35dc24304e to your computer and use it in GitHub Desktop.
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
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