+ 3
Working of *(arg1, arg2) in python in function call.
>>def f(a, b): print a, b >>f(a=1, *(2, )) error: f() has got multiple values for a >>f(1, *(2, )) 1 2 >>f( *(1,2)) 1 2 >>f(a=1, *( ,2)) error: invalid syntax ------>>>>> can someone please explain all these 4 cases and its output. also, please explain the working behind the *( arg1, arg2). and *(arg1, ).?????? thanx in advance. :-)
5 Antworten
+ 6
While testing I found this text related to "variable unpacking", which is faster:
http://caisbalderas.com/blog/JUMP_LINK__&&__python__&&__JUMP_LINK-function-unpacking-args-and-kwargs/
Specifically: "arbitrary arguments will try to >>fill function arguments in order<< therefore may conflict with named arguments". That's what's wrong in your first test.
Test 2 is an unnamed argument + a single-value tuple. I believe this allows Python to apply all of them as a single expansion, leading to no conflict. Notice the linked example:
assert(z=2, *t)
succeeds. z is third in line; the 2-value tuple tries to expand into the first arguments (x, y) and never clobbers z.
Your third example is just star expansion, working as designed; starting at parameter 1 and filling to the right.
Example 4 is an invalid tuple; (,2) is a syntax error--unrelated to star expansion.
+ 4
I'll be able to answer more; mobile's just slow. Take a look at this related example:
def expander(*vars):
... for var in vars:
... print(var)
...
>>> expander(1,2,3,4)
1
2
3
4
Edit: This was intended to show "expansion" of a variable that collects multiple values.
+ 4
I'm working on it--I have to edit in another app; I don't think you're following 'star syntax' rules and I'm trying to prove it without a lot of text.
+ 1
but...I am not getting its connection with my question.
+ 1
oh thanks..@ kirk. now this is something understandable to me.