Home > Net >  Problems of keyword arguments and non-keyword arguments
Problems of keyword arguments and non-keyword arguments

Time:03-28

I'm learning about functions in python recently.

Though the keyword arguments can appear in any order in the list of actual parameters, it is not legal to follow a keyword argument with a non-keyword argument.

It's a quote from 《Introduction to Computation and Programming Using Python》I was wondering why 'it is not legal to follow a keyword argument with a non-keyword argument'? Then I did some research on the order issue in the list of actual parameters in an invocation of a function.

what if my list of actual parameters contains both keyword arguments and positional arguments. Can keyword arguments still appear in random positions as long as the positional arguments stay the same position as the original formal parameter? Or positional arguments can change position too under some sort of rules?

CodePudding user response:

Keyword arguments can appear in random positions as long as they are after the positional arguments and no argument receive a value more than once.

To understand the reasons for these conditions, it should be noted that computers only interpret our commands literally. And when they're confused, they usually try to stop and let us know right away rather than guessing and return a wrong answer.

For instance, we have the following function definition:

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):

With this definition, all arguments can be passed as positional or keyword. Consider this function call: parrot('a', action='b', 'c'). What should the value of action be in this case? While the interpreter/compiler can implement some more logic and the language specification can add some rules to follow in such cases, it would be needlessly complicated. These conditions make it simpler for both the human reading and the computer interpreting/executing the code.

For more details about keyword arguments in Python, I suggest you check out the Python Tutorial: https://docs.python.org/3/tutorial/controlflow.html#keyword-arguments

  • Related