5

I have the following piece of code. In this, I want to make use of the optional parameter given to 'a'; i.e '5', and not '1'. How do I make the tuple 'numbers' contain the first element to be 1 and not 2?

def fun_varargs(a=5, *numbers, **dict):
    print("Value of a is",a)
    for i in numbers:
        print("Value of i is",i)
    for i, j in dict.items():
        print("The value of i and j are:",i,j)

fun_varargs(1,2,3,4,5,6,7,8,9,10,Jack=111,John=222,Tom=333)

3 Answers 3

4

The "idiomatic" Python way to do this is to have the optional argument default to None.

def fun_varargs(a=None, *numbers, **dict):
  if a is None:
    a = 5
  ...

Then you can explicitly choose not to pass it.

fun_varargs(None, 1, 2, 3, 4, 5, some_keyword_arg=":)")

I don't know of a way to actually choose not to pass an optional argument. If you're looking for a practical solution, this is the way to go. But if there's some deeper hackery that lets you bypass the argument altogether, I'd be interested in seeing it as well.

Sign up to request clarification or add additional context in comments.

Comments

3

The .__defaults__ attributes provides default arguments in a tuple. You can use that for here.

>>> def fun_varargs(a = 5, *numbers, **dict):
...     print("value of a is", a)
...     for i in numbers:
...             print("value of i is", i)
...     for i, j in dict.items():
...             print("The value of i and j are:", i,j)
... 

>>> fun_varargs(fun_varargs.__defaults__[0],1,2,3,4,5,6,7,8,9,10,Jack=111,John=222,Tom=333)
value of a is 5
value of i is 1
value of i is 2
value of i is 3
value of i is 4
value of i is 5
value of i is 6
value of i is 7
value of i is 8
value of i is 9
value of i is 10
The value of i and j are: Jack 111
The value of i and j are: John 222
The value of i and j are: Tom 333

Comments

0

One option is to move a after *numbers

def fun_varargs(*numbers, a=5, **dict):
    ...

However, you can no longer use it as a positional argument. fun_varargs(42) would not set a to 42. You can only define a using keyword argument, ie fun_varargs(a=42).

2 Comments

If I swap the position of the parameters, for the above piece of code, the output is that- the numbers 1 to 10 are assigned to the tuple 'numbers'. Why does the compiler not assign 1-9 to 'numbers', 10 to 'a', and the rest to the dictionary?
a is no longer a positional argument in this case. You have to define it using the keyword (a). It would be the same scenario if the function was defined as def fun_varargs(*numbers, **dict, a=5).

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.