braceletboy
braceletboy

Reputation: 98

Python - Pass default values for arguments that are function of other arguments of the function

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.

Upvotes: 4

Views: 126

Answers (4)

Bar Gans
Bar Gans

Reputation: 1653

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

Upvotes: 0

Siddharth Shishulkar
Siddharth Shishulkar

Reputation: 131

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

Upvotes: 0

dedObed
dedObed

Reputation: 1363

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

Upvotes: 7

Denis
Denis

Reputation: 1543

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)

Upvotes: 1

Related Questions