The timing when the value of the default argument is evaluated is different between Ruby and Python.

Sorry for the confusing title. I think it's easier to understand what it means to actually look at the code than to explain it in words. Regarding the environment, Ruby is Ruby 2.0 and Python is Python 3.2.

Well, do you write

Let's try writing this code in Ruby.

#Global variables due to scope
$msg = "Hello, Before World!"

def say(str = $msg)
   puts str
end

say #=> Hello, Before World!

$msg = "Hello, After World!"
say #=> Hello, After World!

The output should be as commented.

If you write similar code in Python, it will look like this.

msg = "Hello, Before World!"

def say(str = msg):
    print(str)

say() #=> Hello, Before World!

msg = "Hello, After World!"
say() #=> Hello, Before World!

The code is similar, but the output of the say function has changed.

Did you get a general idea of the title?

It is a commentary

First, both Ruby and Python can write arbitrary expressions in the default argument values. So, the timing when this value is evaluated is different between Ruby and Python.

In Ruby, ** when a function is called **, In Python, the value of the default argument is evaluated when ** the function is defined **.

$msg = "Hello, Before World!"

def say(str = $msg)
   puts str
end

say() #=> Hello, Before World!

$msg = "Hello, After World!"
say() #=>with this timing$msg is evaluated
    #=>So Hello, After World!
msg = "Hello, Before World!"

def say(str = msg): #At this point msg is evaluated Hello, Before World!It has become
    print(str)

say() #=> Hello, Before World!

msg = "Hello, After World!"
say() #=>Hello because the value of str has already been decided, Before World!

So, the result is the same as before.

Miscellaneous feelings ...

Personally, I think Ruby is more interesting because it can do various things, but both behaviors are * natural *, so it's not bad. (I wonder if Python has to do that because of the VM specifications)

By the way, in Ruby, you can refer to arguments other than the default argument, so by calling itself in the default argument and recursing it,

#Look, this guy recurses with the default arguments ...
def fact(n,ret = n <= 1 ? 1 : fact(n-1) * n)
   ret
end

puts fact(10) #=> 3628800

You can do something like that. Ruby is ... (excuse me).

By the way, it seems that Python uses this property to replace local scope (probably).

say_n = []

for i in range(0,10):
    #say_n.append(lambda: print(i))
    #If so, the value of i will be updated, so it is useless
    say_n.append(lambda j = i: print(j))
    #I need to bind i like this

say_n[2]() #=> 2
say_n[4]() #=> 4

It was a very miscellaneous tip, but if you get hooked on such small differences in specifications for each language, you will not be able to get out of it, so I feel that it is not a loss to know. I hope you remember and find something useful.

Since both Ruby and Python are outsiders, there may be some mistakes. If you find it, I would appreciate it if you could gently bite Hatoo in the comments or on Twitter ([@ alucky0707]).

Reference page

Recommended Posts

The timing when the value of the default argument is evaluated is different between Ruby and Python.
The answer of "1/2" is different between python2 and 3
Indent behavior of json.dumps is different between python2 and python3
Be careful when specifying the default argument value in Python3 series
Make the default value of the argument immutable
Summary of the differences between PHP and Python
Specifying the range of ruby and python arrays
About the difference between "==" and "is" in python
About the * (asterisk) argument of python (and itertools.starmap)
The behavior of @property is different between class definition and old and new styles
[Python of Hikari-] Chapter 06-02 Function (argument and return value 1)
Difference between Ruby and Python in terms of variables
Why is the first argument of [Python] Class self?
[Python Data Frame] When the value is empty, fill it with the value of another column.
What is the default TLS version of the python requests module?
Difference between Ruby and Python split
I compared the speed of Hash with Topaz, Ruby and Python
The story of Python and the story of NaN
I wrote AWS Lambda, and I was a little addicted to the default value of Python arguments
Difference between == and is in python
Build Python environment on Ubuntu (when pip is not the default)
What to do when the value type is ambiguous in Python?
Python> Extract (unpack) the value of list> Add *> You taught me the difference between Python 2 and Python 3 regarding print (* mylist) / print ().
[Python] What is a formal argument? How to set the initial value
[Introduction to Python] What is the difference between a list and a tuple?
When Selenium tells me that the Chrome driver version is different (Python)
Differences between Ruby and Python in scope
[python] [meta] Is the type of python a type?
Differences between Ruby and Python (basic syntax)
Are Php / Ruby / Python that only runs when the file is called directly
I compared the speed of regular expressions in Ruby, Python, and Perl (2013 version)
Divides the character string by the specified number of characters. In Ruby and Python.
The place to be evaluated may be different between map and list comprehension notation
Try to find the probability that it is a multiple of 3 and not a multiple of 5 when one is removed from a card with natural numbers 1 to 100 using Ruby and Python.
What is the difference between `pip` and` conda`?
Correspondence summary of array operation of ruby and python
The value of pyTorch torch.var () is not distributed
Find the divisor of the value entered in python
Compare the speed of Python append and map
This is the only basic review of Python ~ 1 ~
This is the only basic review of Python ~ 2 ~
This is the only basic review of Python ~ 3 ~
A discussion of the strengths and weaknesses of Python
About shallow and deep copies of Python / Ruby
Comparison of Python and Ruby (Environment / Grammar / Literal)
What is the difference between Unix and Linux?
Find the maximum value, minimum value, and number of elements when the integer N is on the first line of the standard input and N integers follow.
Consideration of the difference between ROC curve and PR curve
Around the place where the value of Errbot is stored
[Python] Calculate the average value of the pixel value RGB of the object
The process of installing Atom and getting Python running
Python --Explanation and usage summary of the top 24 packages
[Ruby vs Python] Benchmark comparison between Rails and Flask
What is the difference between usleep, nanosleep and clock_nanosleep?
Visualize the range of interpolation and extrapolation with python
Referencing and changing the upper bound of Python recursion
I checked out the versions of Blender and Python
I checked the default OS and shell of docker-machine
Visualization of the connection between malware and the callback server
Interprocess communication between Ruby and Python (POSIX message queue)
[Django 2.2] Sort and get the value of the relation destination