Search code examples
pythonrecursionrefactoringinspection

Python - can function call itself without explicitly using name?


Or a broader question: how to make a recursive function in python and, when changing its name, it only has to be changed in the declaration?


Solution

  • I found a simple, working solution.

    from functools import wraps
    
    def recfun(f):
        @wraps(f)
        def _f(*a, **kwa): return f(_f, *a, **kwa)
        return _f
    
    @recfun
    # it's a decorator, so a separate class+method don't need to be defined
    # for each function and the class does not need to be instantiated,
    # as with Alex Hall's answer
    def fact(self, n):
        if n > 0:
            return n * self(n-1)  # doesn't need to be self(self, n-1),
                                  # as with lkraider's answer
        else:
            return 1
    
    print(fact(10))  # works, as opposed to dursk's answer