15

Is it possible to define a function argument's default value to another argument in the same function definition? Something like:

def func(a, b=a):
  print a, b

but that didn't work.

2
  • Why not assign a to b in the first line of the function? Commented Nov 4, 2015 at 17:04
  • 3
    You can't do that, you need to do b=None then if b is None: b = a. See stackoverflow.com/q/4575326/3001761 (which you could have found trivially if you'd searched for this...) Commented Nov 4, 2015 at 17:04

1 Answer 1

27

No. This is not possible. The Python interpreter thinks that you want to assign the default value of argument b to a global variable a when there isn't a global variable a.

You might want to try something like this:

def func(a, b=None):
    if b is None:
        b = a
Sign up to request clarification or add additional context in comments.

2 Comments

this wouldn't allow passing only one variable
@EthanBierlein "the best response a good SO contributor can make is to search for duplicates" - i.e. rather than answering.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.