starwish’s diary

pythonのreturn文

仕事や趣味でプログラムを書くことが多い。いつからか気が付かないうちにpythonで関数からreturnするとき、

def func():
  return (1)
print(func())

という感じで戻り値を()に入れる癖がついていて、先日returnは関数ではないので()に入れる必要はないと指摘され気が付いた。
ドキュメントを見直すと6.2.3. Parenthesized form
A parenthesized expression list yields whatever that expression list yields: if the list contains at least one comma, it yields a tuple; otherwise, it yields the single expression that makes up the expression list.
との記述があった。(x)はx、(x,)はtuple([x])ということ。pythonを始めたときになぜtupleだけ要素が一つでも','がいるのか謎だったが、そういうことか。