Reputation: 817
if you write the code like:
def test(x,y,z):
return x+y
test(y=10,5,8)
It would raise the error:
SyntaxError: positional argument follows keyword argument
So it seems this is the rule that everyone knows ,however, I haven't found the clear and intuitive explanations about this.
What I think is that y is keyword argument,and then follow the order of arguments ,so x would be 5 and z would be 8.
I wonder the reason why we can't do this,is there ant part that would confuse the compiler?
If an example can be showed,it would be really awesome!
Upvotes: 2
Views: 58
Reputation: 4674
It's a Python compiler limitation to reduce the need for under-the-hood dictionary lookups. There's not actually an ambiguous case or anything they're avoiding.
You can see where the dict lookup would need to happen though:
def test(x, y):
return x + y
test(y=10, 5)
Follow the compiler from top-left to bottom-right...
With kwargs allowed to come before positional args:
y=10
kwargs
dict (expensive).5
.x
is in kwargs
dict (expensive).x
positional arg.Without wkargs allowed before positional args:
y=10
kwargs
dict (expensive).5
.Now consider the case where plain arguments are used, which (can be) fast.
def test(x, y):
return x + y
test(10, 5)
Keywords first allowed:
10
.kwarg
dict for x
(expensive).x
arg.5
.kwarg
dict for y
(expensive).y
arg.Args must be first:
10
.x
arg.5
.y
arg.This difference isn't compiled out in Python, because the byte-code still allows for dynamic function calls. Python devs decided to forbid keyword-first syntax to make the language a little faster at run time.
PS: There is also an argument that putting keywords before positional args is harder to read, but I'll leave aesthetic judgements to the critics. I think it looks fine.
Upvotes: 1