The Gritty Details

If you choose to use and combine the special argument-matching modes, Python will ask you to follow these ordering rules:

 

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

 
  • In a function call, arguments must appear in this order: any positional arguments (value), followed by a combination of any keyword arguments (name=value) and the *sequence form, followed by the **dict form.
  • In a function header, arguments must appear in this order: any normal arguments (name), followed by any default arguments (name=value), followed by the *name (or * in 3.0) form if present, followed by any name or name=value keyword-only arguments (in 3.0), followed by the **name form.

In both the call and header, the **arg form must appear last if present. If you mix arguments in any other order, you will get a syntax error because the combinations can be ambiguous. The steps that Python internally carries out to match arguments before assignment can roughly be described as follows:

 

 
  1. Assign nonkeyword arguments by position.
  2. Assign keyword arguments by matching names.
  3. Assign extra nonkeyword arguments to *name tuple.
  4. Assign extra keyword arguments to **name dictionary.
  5. Assign default values to unassigned arguments in header.

After this, Python checks to make sure each argument is passed just one value; if not, an error is raised. When all matching is complete, Python assigns argument names to the objects passed to them.

The actual matching algorithm Python uses is a bit more complex (it must also account for keyword-only arguments in 3.0, for instance), so we’ll defer to Python’s standard language manual for a more exact description. It’s not required reading, but tracing Python’s matching algorithm may help you to understand some convoluted cases, especially when modes are mixed.


Note

In Python 3.0, argument names in a function header can also have annotation values, specified as name:value (or name:value=default when defaults are present). This is simply additional syntax for arguments and does not augment or change the argument-ordering rules described here. The function itself can also have an annotation value, given as def f()->value. See the discussion of function annotation in Chapter 19 for more details.