LoginSignup
3
0

More than 3 years have passed since last update.

Pythonのデフォルト引数の挙動

Last updated at Posted at 2020-09-02

Pythonのデフォルト引数はメソッド実行時ではなくプログラム起動時に評価される
これまで使っていたRubyやScalaでの挙動が普通だと思っていたので、何がおかしいのかわからずにかなりハマった

Ruby

def test(t=Time.now)
  puts(t)
end

test
sleep(10)
test

実行結果

2020-09-02 09:05:42 +0900
2020-09-02 09:05:52 +0900

Scala

object Test {
  def test(t: DateTime = DateTime.now()): Unit = {
    println(t)
  }

  def run(): Unit = {
    test()
    Thread.sleep(10000)
    test()
  }
}
2020-09-02T09:14:08.681+09:00
2020-09-02T09:14:18.732+09:00

Python

import datetime
import time

def test(t=datetime.datetime.now()):
    print(t)

test()
time.sleep(10)
test()
2020-09-02 09:20:40.970098
2020-09-02 09:20:40.970098

他の言語はどうなんだろう

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