What is a function parameter =[] for?

Chris Angelico rosuav at gmail.com
Tue Nov 24 07:07:34 EST 2015


On Tue, Nov 24, 2015 at 10:36 PM, Antoon Pardon
<antoon.pardon at rece.vub.ac.be> wrote:
>>> So, looking at some source code, a default value for certain types is only
>>> certain to be that value for the very first call of that function?
>>
>> On the contrary, it is certain always to be that exact object.
>
> No, he is talking about the value. Since the object can be mutated
> and thus have an other value, his statement seems correct.

With mutable objects, you can *never* depend on their values. Any time
ANY byte code gets executed, the value could change. That's why I have
never said anything about *values* of arg defaults - what you're
promised is that the *object* will be the same (so, I'm looking at its
identity, rather than its value). So it's not even certain to be that
value even for the first call:

def create_user(name, email, creation_time=datetime.datetime.now()):

Looks perfectly reasonable, right? And with late binding, sure! But
with early binding, this will probably NEVER be what you want. But
what if you have an object that always stringifies the current time?

class Now:
    def __init__(self, fmt):
        self.fmt = fmt
    def __repr__(self):
        return datetime.datetime.now().strftime(self.fmt)

def create_user(name, email, creation_time=Now("%Y%m%d%H%M%S")):

Voila! An object whose value dynamically represents the notion of
"Now", but where it makes fine sense to have the same object used
every time. Since the value changes every second, it (probably) won't
even have that value for the first call, yet the behaviour will be
correct.

His statement is still incorrect, in that the value is NEVER certain,
but the identity is ALWAYS certain. It happens to be the case for the
one example of lists that get mutated only in the function. It's about
as accurate as the statement that Python is pass-by-value for integers
but pass-by-reference for dictionaries.

ChrisA



More information about the Python-list mailing list