1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Python]デフォルト引数の順序制限

Last updated at Posted at 2021-04-01

関数にデフォルト引数を持たせる場合、
左側の引数(a)にのみデフォルト引数を持たせることはできない。

Python
# SyntaxError
def foo(a=1, b):
    return a + b
SyntaxError: non-default argument follows default argument 

このような場合は、
デフォルト引数を右にずらす

Python
def foo(b, a=1):
    return a + b
>>> foo(2)
3

また、下の方法も使える。

Python
def foo(*, a=1, b):
    return a + b

ただし、呼び出し時に変数指定が必要

>>> foo(b=2)
3
>>> foo(2)
TypeError: ...

参考:
https://qiita.com/scapegoat_11_/items/fafea1a0c7daaf43849e
https://docs.python.org/ja/3.6/reference/compound_stmts.html#index-21

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?