LoginSignup
1
2

More than 5 years have passed since last update.

python3 SyntaxError: non-default argument follows default argumentはなぜ起こるのか

Posted at

すっかり忘れていたのか、久しぶりにこのエラーに引っかかったので備忘録がてらメモ。

default argumentとは

デフォルトで値が与えられている引数のこと。色々な使い方があるが不確実なイベントに対応するためのプレースホルダーとして使ったり用途は様々。

def myfunc(value=None):
    if value is None:
        value = []
    # modify value here

結局このエラーは何を言っているのか

引数の数 > 1という前提において、default argument(def foo(x, y, default_arg=1): return default_arg, y, x,←の一番右の引数)はルールとして最初の引数として配置できませんよと言う意味。

なぜか

結論から言うと引数同士の混乱を防ぐため。SOFで素晴らしい回答を見つけたのでそれを引用しておく。

def fun1(a="who is you", b="True", x, y):
...     print a,b,x,y

Suppose its allowed to declare function as above, Then with the above declarations, we can make the following (regular) positional or keyword argument calls:

func1("ok a", "ok b", 1)  # Is 1 assigned to x or ?
func1(1)                  # Is 1 assigned to a or ?
func1(1, 2)               # ?

How you will suggest the assignment of variables in the function call, how default arguments are going to be used along with keyword arguments.

>> def fun1(x, y, a="who is you", b="True"):
...     print a,b,x,y
... 

defaultなのかそうでないのかの線引きをするためにdefault argumentは最後に配置するよう定められているわけだ。

参考

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2