When using a function as a default argument, why is that function always called?

76 views Asked by At

I want to have a function that I can call it with or without an argument, using another function to get the argument value in case it is missing.

I already tried this:

def GetValue():
...

def Process (value = GetValue):
...

I tried to call the function Process with Process() and Process(105) but it called the function GetValue either way.

1

There are 1 answers

1
Samwise On

Anything on the def line is executed when the function is defined. You want to call GetValue inside the Process function so that it’s only called when the condition is met for a specific argument value:

def GetValue():
    ...

def Process(value = None):
    if value is None:
        value = GetValue()
    ...