Python's default arguments are evaluated at program startup, not at method execution </ b> I thought that the behavior in Ruby and Scala that I used so far was normal, so I was quite addicted to it without knowing what was wrong.
Ruby
def test(t=Time.now)
  puts(t)
end
test
sleep(10)
test
Execution result
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
What about other languages?
Recommended Posts