Late-binding of function defaults (was Re: What is a function parameter =[] for?)

Chris Angelico rosuav at gmail.com
Wed Nov 25 08:35:38 EST 2015


On Wed, Nov 25, 2015 at 11:35 PM, BartC <bc at freeuk.com> wrote:
> One gotcha at least is well known. Where, in a language of the least
> surprises, you might write:
>
>  d1 = date (25,12,2010)
>  d2 = d1
>  d2.year += 1
>
> You would expect d1 and d2 to represent a period one year apart. In Python,
> they would both be the later date.

I'm not sure why this is "a language of least surprises". It's just a
language of *different* surprises. I'll give you an example of exactly
that: PHP has semantics similar to what you're describing.

$ php
<?php
$a = array("foo", "bar");
$b = $a;
$b[1] = "baz";
print_r($a);
^D
Array
(
    [0] => foo
    [1] => bar
)

I'm not exactly sure of the definition of PHP's assignment, as it's
been a while since I looked it up; but it seems to be something like
what you're describing. This seems well and good, until you start
contemplating gigantic arrays and what happens when you pass them from
one function to another. What're your performance expectations? With
Python, I know that "a = b" happens in constant time, and I also know
that the performance of "a[1]=2" is not going to be affected by any
other names that might be bound to the same object. PHP's references
make this even more messy:

$ php
<?php
$a = array("foo", "bar");
$b = &$a[1];
$b = $a;
$b[1] = "baz";
print_r($a);
^D
Array
(
    [0] => foo
    [1] => baz
)

So... since I'd previously set $b to be a reference, now assigning to
it does something different. And what, exactly? Is $a[1] the exact
same array as $a? Has any copying happened? When I change $b[1], is
that the same as changing $a[1], or is it actually changing $a[1][1],
and is that even any different?

This isn't a magical solution to all surprises, except perhaps in that
you've built a language yourself, so it conforms perfectly to *your*
expectations. You can never make something that fits everyone's
expectations, so you'll always have surprises somewhere. It's just a
question of where, and how easily they can be explained when someone
runs into them.

ChrisA



More information about the Python-list mailing list