I'm looking for a Python decorator that can make a function recursive. I find myself writing a lot of functions like this:
def xyz(data):
if not isinstance(data, TypeThatDenotesSingularity):
return map(xyz, data)
return singular_xyz(data)
I figure there must be a decorator out there somewhere (in the standard library?) that can slim down the notation a tad:
@recursive(TypeThatDenotesSingularity)
def xyz(data):
return singular_xyz(data)
I have been searching but I can't seem to get anywhere. Perhaps I'm missing some essential terminology?
Thanks for pointing me in the right direction!
How about this:
def recursive(stop_type):
def _inner(func):
def _recursive(data, *args, **kw):
if not isinstance(data, stop_type):
return map(_recursive, data)
return func(data, *args, **kw)
return _recursive
return _inner
Explanation of how this works if used as @recursive(MySingularType)
MySingularType
_inner
_inner
is immediately called with the function to decorate, also at compile time_inner
returns closure _recursive
which is now the new function which is called when you call your decorated functionNow, when you call your function: _recursive
is called. If the type matches, return the function result. Otherwise, map another call to _recursive, ad infinitum (well really ad until stackoverflowium)
Note You can omit the *args
and **kwargs
if the decorated function will always always only take a single value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With