2

I want to define a function with some optional arguments, let's say A (mandatory) and B (optional). When B is not given, I want it to take the same value as A. How could I do that?

I have tried this, but it doesn't work (name 'B' is not defined):

def foo(A, B=A):
 do_something()

I understand that the values of the arguments are not assigned before the body of the function.

asked Jan 27, 2016 at 0:34

2 Answers 2

8

You shall do this inside of your function.

Taking your original function:

def foo(A, B=A):
 do_something()

try something like:

def foo(A, B=None):
 if B is None:
 B = A
 do_something()

Important thing is, that function default values for function arguments are given at the time, the function is defined.

When you call the function with some value for A, it is too late as the B default value was already assigned and lives in function definition.

answered Jan 27, 2016 at 0:37
Sign up to request clarification or add additional context in comments.

Comments

1

You could do it like this. If B has a value of None then assign it from A

def foo(A, B=None):
 if B is None:
 B = A
 print 'A = %r' % A
 print 'B = %r' % B
answered Jan 27, 2016 at 0:38

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.