Pro_gram_mer
Pro_gram_mer

Reputation: 817

An intuitive way to understand positional argument should not follow keyword argument

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

Answers (1)

Pi Marillion
Pi Marillion

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:

  1. Read y=10
  2. Put into kwargs dict (expensive).
  3. Read 5.
  4. Check if first positional arg name x is in kwargs dict (expensive).
  5. Put into x positional arg.

Without wkargs allowed before positional args:

  1. Read y=10
  2. Put into kwargs dict (expensive).
  3. Read 5.
  4. Throw and error (easy?)

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:

  1. Read 10.
  2. Check kwarg dict for x (expensive).
  3. Put in x arg.
  4. Read 5.
  5. Check kwarg dict for y (expensive).
  6. Put in y arg.

Args must be first:

  1. Read 10.
  2. Put in x arg.
  3. Read 5.
  4. Put in 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

Related Questions