Python decoder for simple recursion? In the standard library or elsewhere?

I am looking for a Python decorator that can make a function recursive. I find that I am writing a lot of such functions:

def xyz(data): if not isinstance(data, TypeThatDenotesSingularity): return map(xyz, data) return singular_xyz(data) 

I suppose there should be a decorator somewhere (in the standard library?) That can reduce the tad notation:

 @recursive(TypeThatDenotesSingularity) def xyz(data): return singular_xyz(data) 

I searched, but it seems I can’t find anything. Perhaps I am missing some essential terminology?

Thanks for pointing me in the right direction!

+6
python decorator recursion
source share
2 answers

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 

An explanation of how this works if it is used as @recursive(MySingularType)

  • recursive is called at function decoration time with the stop_type argument set to MySingularType
  • _inner recursive return _inner
  • _inner immediately called with a function to decorate, also at compile time
  • _inner returns a closure of _recursive , which is now a new function called when your decorated function is called

Now when you call your function, _recursive is _recursive . If the type matches, return the result of the function. Otherwise, map another call to _recursive, ad infinitum (well, really an ad before stackoverflowium)

Note You can omit *args and **kwargs if the decorated function always always takes only one value.

+3
source share

I do not know about the decorator, but you can do it with the class if you rewrite the same template over and over again.

 class Recursive(object): def __init__(self, check_type, singular): self.check_type = check_type self.singular = singular def __call__(self, data): if not isinstance(data, self.check_type): return map(self, data) return self.singular(data) 
+1
source share

All Articles