[RUBY] Python default argument behavior

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

Python default argument behavior
Python default argument trap
[python] behavior of argmax
Python function argument summary
blender, python, sphere behavior
[Python] Chapter 03-02 turtle graphics (turtle behavior)
Command line argument processing (Python docopt)
[python] Callback function (pass function as argument)
Check the behavior when assigning Python
Function argument type definition in python
Python
Behavior when listing in Python heapq
Change python default encoding to utf-8
Behavior of python3 by Sakura's server
Basic Python operation 2nd: Function (argument)
[Raspberry Pi] Changed Python default to Python3
[Python] Easy argument type check with dataclass
Check the behavior of destructor in Python
python> link> strftime () and strptime () behavior / code
Python strings become f strings by default (maybe)
⚠️ Be careful with Python's default argument values ⚠️
To set default encoding to utf-8 in python
[python, multiprocessing] Behavior for exceptions when using multiprocessing
Make the default value of the argument immutable