1

This is my code. I was observing data type of args in def function.

>>> def example(a,b=None,*args,**kwargs):
...   print a, b
...   print args
...   print kwargs
...
>>> example(1,"var",2,3,word="hello")
1 var
(2, 3)
{'word': 'hello'}
>>> _args = (1,2,3,4,5)
>>> _kwargs = {"1":1,"2":2,"3":3}
>>> example(1,"var",*_args,**_kwargs)
1 var
(1, 2, 3, 4, 5)
{'1': 1, '3': 3, '2': 2}

When the 2, 3 of actual parameters (arguments) to a function pass as *arg of formal parameters; thus, arguments are passed using call by value (where the value is always an object reference, not the value of the object).

*args in the call expands each element in my sequence (be it tuple or list) into separate parameters. Those separate parameters are then captured again into the *args argument, why is it always a tuple?

Burger King
  • 2,945
  • 3
  • 20
  • 45
  • You also *called* the function with `*args` in the call syntax. That is a separate syntax, mirroring the function signature. Pass in the list *as one argument* instead, so `example('a', 'b', ['foo', 'bar'])`. – Martijn Pieters Apr 03 '15 at 15:54
  • Do you really understand my question? I doesn't quest how to pass to `*args`. –  Apr 03 '15 at 15:57
  • All the arguments before a keyword arg and after `a` and `b` will assumed as `args` and python will return them in a tuple, and when you pass `*_args` to your function actually you have unpacked your args! if you want to it print a list or ... you can pass your argument within a list like `[2,3]` then the result will be `([2,3],)`. – Mazdak Apr 03 '15 at 15:59
  • `*args` in the *call* expands each element in your sequence (be it tuple or list) into separate parameters. Those separate parameters are then captured again into the `*args` *argument*, which is always a tuple. – Martijn Pieters Apr 03 '15 at 15:59
  • @Pythoneer: if you wanted to pass in a list `args` as a separate argument, don't use `*args` in the call. – Martijn Pieters Apr 03 '15 at 16:00
  • @MartijnPieters I got it. I doesn't focus args with/without star in different. –  Apr 03 '15 at 16:04
  • @MartijnPieters I want to know you said `Those separate parameters are then captured again into the *args argument, which is always a tuple.`. May you more explain? –  Apr 03 '15 at 16:08
  • @Pythoneer: Sorry, I am having a hard time understanding your English. As a result, I am not confident you understand what I am writing either. I am not sure I can help you out here. – Martijn Pieters Apr 03 '15 at 16:12
  • @MartijnPieters I know my writing is poor in English, but reading is no problem. I think it is keyword and can solve my problem. –  Apr 03 '15 at 16:20

0 Answers0