LoginSignup
0
0

More than 5 years have passed since last update.

Python > positional arguments / keyword arguments > mix可能 > print(2, 3, 5, 7, 11, sep='\t', end='')

Last updated at Posted at 2017-03-29

@ Introducing Python: Modern Computing in Simple Packages by Bill Lubanovic
(No. 2503 / 12833)

以下の2つのargumentがある。

  • positional arguments
  • keyword arguments

位置引数 (positional argument、固定引数)
実引数 を参照してください。

...

keyword argument
実引数 を参照してください。

...

You can mix positional and keyword arguments.

2つのargumentの混合 > 失敗

def check_inputs(name1, value1, name2, value2):
    print('%s: %s' % (name1, value1))
    print('%s: %s' % (name2, value2))

# mixing of [keyword] and [positional] arguments
check_inputs(value1=3.1415, name1="pi", "napier", 2.718)
結果
Compilation error   time: 0 memory: 23288 signal:0
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python2.7/py_compile.py", line 117, in compile
    raise py_exc
py_compile.PyCompileError:   File "prog.py", line 6
    check_inputs(value1=3.1415, name1="pi", "napier", 2.718)
SyntaxError: non-keyword arg after keyword arg

keyword argumentの後にpositional argumentはダメとのこと。

2つのargumentの混合 > 成功

def check_inputs(name1, value1, name2, value2):
    print('%s: %s' % (name1, value1))
    print('%s: %s' % (name2, value2))

# mixing of [positional] and [keyword] arguments
check_inputs("pi", 3.1415, value2=2.718, name2="napier")
結果
Success time: 0 memory: 23288 signal:0
pi: 3.1415
napier: 2.718

余談 > 備考

何故、keyword argument, positional argumentだとダメか。

考えたのは、positional argumentが後ろにある場合、どのインデックスのargumentかを判別するのが難しいのだと思う。

先にpositional argumentがある場合は、インデックスの0から逐次判別していき、途中にkeyword argumentになれば、そこからkeyword argumentの処理を可能。

mixを使うかどうか

個人的には使おうと思わない (2017年3月29日現在)。
一貫性がくずれるからソースを読みにくくするように感じている。

うまい使い方があれば、使うかもしれない。

教えていただいた事項

@shiracamus さんのコメントにてpositional arguments / keyword argumentsのmixの用途を教えていただきました。

情報感謝です。

0
0
2

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
0
0