Search code examples
pythonrecursiondefault-parameters

Are there any ways around default parameters needing to be declared at compliation in python?


So I was working on a bit of code and found that when defining things recursively you can't have a method with a default variable based off of a passed in variable. A bit of surface level research shows that Python requires these to be declared at compilation. As such the following is not allowed.

    def foo(bar, potato = bar*bar):

        if(bar is 0): return potato
        potato -= bar
        return foo(bar-1, potato)

The code is hogwash. But if it worked it would return (bar*(bar-1))/2.

I know I could simply manually pass in potato, but are there other ways of making something similar to this work without using a global, or initially declaring potato?


Solution

  • You can do sth along the following lines which constitute an oft-seen pattern. Make the default parameter None and set it to the dependent value if appropriate inside the function:

    def foo(bar, potato=None):
        if potato is None:
            potato = bar * bar  
        if bar == 0: 
            return potato
        potato -= bar
        return foo(bar-1, potato)
    

    And if you are greedy with lines you can use the ternary if-else operator:

    def foo(bar, potato=None):
        potato = bar * bar if potato is None else potato
        return potato if bar == 0 else foo(bar - 1, potato - bar)