4

I would like to write a function in which the default value of one argument is a function of some arguments that are being passed to the same function. Something like this:

def function(x, y = function2(x)):
    ##definition of the function

Is it possible to write such a function in Python? I came across this answer for c++. But there is no method overloading in Python

Thanks in advance.

4 Answers 4

7

A pretty usual way of solving this is by using None as a placeholder:

def function(x, y=None):
    if y is None:
        y = f2(x)

    pass  # whatever function() needs to do
Sign up to request clarification or add additional context in comments.

1 Comment

Also, this would be the best way of setting default values for some mutabe typed variable.
1

This makes no sense. hat are you trying to achieve? What is the Y? Is taht function? then you must write:

def function(x, y = function2):
    ##definition of the function

If the Y is a simple value then you must write:

def function(x, y = None):
    if y is None:
         y = function2(x)

Comments

0

I don't know what exactly are you trying to achieve here use case wise but you can use a decorator that does what is required for you.

A silly example is here https://repl.it/@SiddharthShishu/IntrepidPunctualProspect

Comments

0
def function(x, y=None):
    if y is None:
        y = f2(x)

1 Comment

Keep in mind, that this would work if such values as zeroes, empty collections and other stuff which evaluate to False is NOT a valid value for y.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.