0
2

More than 1 year has passed since last update.

Python 気持ちが悪い、引数への値の渡し方

Last updated at Posted at 2023-01-27

下のコードにおいて、「気持ちが悪い」とコメントしたところ。ちゃんと動くが、気持ちが悪い。

def func(a, b, c=3, d=4):
    print(a, b, c, d)

# OK
func(1, 2)
# 1 2 3 4

# OK
func(1, 2, c=-1, d=5)
# 1 2 -1 5

# OK
func(1, 2, d=5, c=-1)
# 1 2 -1 5

# 気持ちが悪い
func(1, 2, -1)
# 1 2 -1 4

# 気持ちが悪い
func(1, 2, -1, 5)
# 1 2 -1 5

# 気持ちが悪い
func(a=1, b=2)
# 1 2 3 4

# 気持ちが悪い
func(b=2, a=1)
# 1 2 3 4

# 気持ちが悪い
func(c=-1, b=2, a=1)
# 1 2 -1 4

一応、下のようにすれば、「気持ちが悪い」のパターンでerrorを発生させることができるらしい。

def func2(a, b, /, * , c=3, d=4):
    print(a, b, c, d)

# OK
func2(1, 2)
# 1 2 3 4

# 気持ちが悪い
func2(c=-1, b=2, a=1)
# TypeError: func() got some positional-only arguments passed as keyword arguments: 'a, b'

参考:https://docs.python.org/ja/3.8/whatsnew/3.8.html

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