-1

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.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
hirata1
  • 7
  • 1
  • 4
    To confirm, is your example really `value=GetValue` or `value=GetValue()`? – Gino Mempin Aug 09 '23 at 04:04
  • 1
    This is a FAQ and your example does not behave as you described. The `GetValue` function would only be called regardless of the actual invocation of `Process` if you had defined it as `def Process(vaue=GetValue())`. Furthermore, your question is not a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). So I am downvoting your question. **Do not waste our time** asking for help with code that is different than your put in your question. – Kurtis Rader Aug 09 '23 at 04:37
  • Does this answer your question? [Python: default value of function as a function argument](https://stackoverflow.com/questions/71305358/python-default-value-of-function-as-a-function-argument) or [Python function default argument random value](https://stackoverflow.com/questions/62412902/python-function-default-argument-random-value) – Abdul Aziz Barkat Aug 09 '23 at 05:02

1 Answers1

2

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()
    ...
Samwise
  • 68,105
  • 3
  • 30
  • 44
  • 1
    Your answer is fine but you failed to notice that the question does not actually call `GetValue` when the `Process` function is defined. – Kurtis Rader Aug 09 '23 at 04:36