Can Python function return multiple data?

Chris Angelico rosuav at gmail.com
Thu Jun 4 17:44:25 EDT 2015


On Fri, Jun 5, 2015 at 3:11 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> You need at least one more test to prove pass by value: you need to
> demonstrate that the value bound to y is copied when passed to the
> function. E.g. pass a mutable value (say, a list) and mutate it inside the
> function. If the list in the outer scope is *not* mutated, then and only
> then can you say it is pass by value.

Minor quibble: This discussion is about semantics, not timing. A
language can use pass-by-value but with optimizations for the
read-only case.

$ cat array_argument.php
<?php
function readonly($arr) {if ($arr[1] != 1) echo "WRONG!\n";}
function readwrite($arr) {$arr[1] = 1;}

$array = array();
//Populate a big array
for ($i=0; $i<1000; ++$i) $array[$i] = $i;

//Now pass it repeatedly as an argument
$start = microtime(1);
for ($i=0; $i<100000000; ++$i) readonly($array);
$i/=1000000;
$t = (microtime(1)-$start);
echo "Read-only: $i million iterations in $t seconds\n";

$start = microtime(1);
for ($i=0; $i<100000; ++$i) readwrite($array);
$i/=1000;
$t = (microtime(1)-$start);
echo "Read-write: $i thousand iterations in $t seconds\n";

$ time php array_argument.php
Read-only: 100 million iterations in 11.251608133316 seconds
Read-write: 100 thousand iterations in 2.6384630203247 seconds

real 0m13.914s
user 0m13.780s
sys 0m0.000s


PHP passes arrays by value, but optimizes away the copy in the
read-only case - which means that array mutations can trigger
unexpected copying. But it's still pass-by-value, even though you can
appear to have the performance of pass-by-object/pass-by-reference.
Conceivably, a language might implement pass-by-value by having a
"shadow" that knows that it's "the same as that array only this one
got changed", although I can't imagine it'd be efficient for
real-world work. It'd still be legitimate pass-by-value though.

ChrisA



More information about the Python-list mailing list