Why can't non-default parameters follow default parameters

JunePyo Suh·2020년 4월 21일
0

There are several ways to take arguments in python.

1. Positional arguments

2. Keyword arguments

3. Mixing positional and keyword arguments


*the order of positional parameters should be respected

4. Default value parameters

Why can't non-default parameters follow default parameters in python

The image below shows a compiling rule that Python interpreter adheres to. The order of parameters that should be followed when declaring a function is:

positional parameter->keyword parameter->default parameter->keyword-only parameter

When a default parameter precedes non-default parameters at the point of function declaration, the interpreter reads the function sequentially and will recognize such order of parameter declaration as illegal. Then it will throw a SyntaxError even before the function is called.

One interesting point is that according to the rule, keyword-only parameters, which are technically non-default parameters, can come after default arguments.
To have keyword-only parameters after the default arguments, the above rule must be strictly followed. If not, the interpreter will throw an error, for keyword parameters look exactly the same as regular positional arguments at the function declaration stage and the interpreter won't be able to differentiate the keyword argument with positional arguments.

  • Syntax error is thrown because variable length positional argument "*more" is missing

  • when "*more" is included in the code, no error occurs

Side note: variable lenth positional argument parameter uses tuple; variable length keyword argument parameter uses dictionary

further reading: https://getkt.com/blog/python-keyword-only-arguments/

a = 23

0개의 댓글