2

Given a function with multiple arguments, where all but the first one are variable.

E.g.: def f(a, b = .., ...)

I am looking for minimalist python-code that realizes the intuitive code below:

def f(a, b = a, ...)

Hence, I could not find any satisfying answers I am asking here although I am without doubts that the answers to this question have been given already somewhere - in that case i apologize. Cheers!

I specify by another example my desired functionality again intuitively by wrong code:

def f(a,b,c, d = 0, e = [], f = b, g = c, h = a):
...

Thank you in advance!

2
  • So you want the default of one parameter to be the value passed to another? Commented Nov 23, 2019 at 12:24
  • Yes, exactly :) Commented Nov 23, 2019 at 13:57

1 Answer 1

1

According to the Python docs:

the expression [used as default parameter value] is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call.

So what you are trying to achieve would not work so simply because default parameter values are computed only once at the function definition, not at every call.

Instead, you can set all default parameter values to None and test for this value in the body of the function:

def func(a, b, c, d = 0, e = [], f = None, g = None, h = None):
    f = b if f == None else f
    g = c if g == None else g
    h = a if h == None else h
Sign up to request clarification or add additional context in comments.

2 Comments

I don't think so. Also you should probably remove the answer you posted as a comment:)
- a touch of fastidiousness I wanna respect :D

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.