2

I'm using python 3.3. Consider this function:

def foo(action, log=False,*args) : print(action) print(log) print(args) print() 

The following call works as expected:

foo("A",True,"C","D","E") A True ('C', 'D', 'E') 

But this one doesn't.

foo("A",log=True,"C","D","E") SyntaxError: non-keyword arg after keyword arg 

Why is this the case?
Does this somehow introduce ambiguity?

0

2 Answers 2

6

Consider the following:

def foo(bar="baz", bat=False, *args): ... 

Now if I call

foo(bat=True, "bar") 

Where does "bar" go? Either:

  • bar = "bar", bat = True, args = (), or
  • bar = "baz", bat = True, args = ("bar",), or even
  • bar = "baz", bat = "bar", args = ()

and there's no obvious choice (at least between the first two) as to which one it should be. We want bat = True to 'consume' the second argument slot, but it's not clear which order the remaining arguments should be consumed in: treating it as if bat doesn't exist at all and moving everything to the left, or treating it as if bat moved the "cursor" past itself on to the next argument. Or, if we wanted to do something truly strange, we could defend the decision to say that the second argument in the argument tuple always goes with the second positional argument, whether or not other keyword arguments were passed.

Regardless, we're left with something pretty confusing, and someone is going to be surprised which one we picked regardless of which one it is. Python aims to be simple and clean, and it wants to avoid making any language design choices that might be unintuitive. There should be one-- and preferably only one --obvious way to do it.

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

Comments

1

The function of keyword arguments is twofold:

  1. To provide an interface to functions that does not rely on the order of the parameters.
  2. To provide a way to reduce ambiguity when passing parameters to a function.

Providing a mixture of keyword and ordered arguments is only a problem when you provide the keyword arguments before the ordered arguments. Why is this?

Two reasons:

  1. It is confusing to read. If you're providing ordered parameters, why would you label some of them and not others?
  2. The algorithm to process the arguments would be needless and complicated. You can provide keyword args after your 'ordered' arguments. This makes sense because it is clear that everything is ordered up until the point that you employ keywords. However; if you employ keywords between ordered arguments, there is no clear way to determine whether you are still ordering your arguments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.