LoginSignup
3
4

More than 5 years have passed since last update.

任意引数と*args, **kwargs

Posted at

任意引数の後ろに*args, **kwargsを置くのはok

*argsの前に任意引数を置くことは可能。
以下のコードは通る。

optionalarg.py
def foo(x=10, *args, **kwargs):
    return x, args, kwargs


print foo(12, 13, 14) 
#=> (12, (13, 14), {})

しかし、任意引数の後ろに必須引数を定義することはできない。
以下のコードは構文エラーになる。

syntaxerror.py
def foo(x=10, y, *args, **kwargs):
    return x, y, args, kwargs
# SyntaxError: non-default argument follows default argument

「任意引数」と「名前付き引数」という用語について

任意引数と名前付き引数という用語があるが、どう使い分けるべきなのだろうか?

『Dive In Python』を読むと以下のように推測できる。

  1. 関数の定義に使う場合は「任意引数」。「必須引数」の対概念。
  2. 関数の呼び出しに名前を指定する場合は「名前付き引数」。

(リンク: 英語版読むの面倒なのでcocoatomoの翻訳版)
http://cocoatomo.iza-yoi.net/DIP/power_of_introspection/optional_arguments.html

3
4
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
3
4