lambda

Antoon Pardon apardon at forel.vub.ac.be
Mon Jan 17 09:51:55 EST 2005


Op 2005-01-17, Just schreef <just at xs4all.nl>:
> In article <slrncunejk.36o.apardon at rcpc42.vub.ac.be>,
>  Antoon Pardon <apardon at forel.vub.ac.be> wrote:
>
>> Op 2005-01-17, Steve Holden schreef <steve at holdenweb.com>:
>
>> > There you go with the minutiae again. How about:
>> >
>> > "Don't use mutables as hash keys"?
>> 
>> That sounds too dogmatic to my ears. I also find it
>> too selective. The problem with mutables as dictionary
>> keys is not specific to dictionaries. Everywhere you
>> have mutables in a container, it is possible that
>> mutating the object in the container will cause
>> problem.
>
> The main difference is: if you mutate a dict key you *always* have a 
> problem. So don't do that. Mutating (say) a list item *only* is a 
> problem if you (say) need that list to remain sorted.

That is not true. It is a problem every time I expect the list
items to remain the same.

> Lists don't 
> magically remain sorted, so people generally sort it before they do some 
> operation that expects a sorted list.
>
>> Heck even using mutables as arguments can
>> cause trouble. Why else the specific advice against
>> 
>>   def foo(p = [])
>> 
>> type of arguments. So should we adopt the principles:
>> 
>>   Don't use mutables in containers
>
> Nonsense.
>
>>   Don't use mutables as default values for parameters
>
> That's good advice in general.
>
>>   Don't use mutables as arguments.
>
> Nonsense.
>
>>   Don't assign one mutable to an other.
>
> Nonsense. Some newbies get surprised by Python's assignment-doesn't-copy 
> semantics, but it's such basic knowledge (as well as a useful feature) 
> that I simply don't understand you saying this.

Well it is this same sematics that causes the problems with
mutable dictionary keys. If it is such basic knowledge then what
is the problem with mutable dictionary keys?

>> I don't see a big difference between these principles
>> and the hash key principle,
>
> Than you haven't looked hard enough.

All of these can get unexpected behaviour because of the
assignment-doesn't-copy semantics. The same semantics
that can cause problems if you work with mutable dictionary
keys.

>> so in the end may be we
>> should just stick with the more general principle:
>> 
>>   Don't use mutables!
>> 
>> and be done with it.
>
> Ok, so you're indeed a troll.

The problems with mutables as dictionary keys is just one
particulary case of the problems you can have when your
assignmentxs semantics just creates a new reference to the
same object. As such it is no different from the problem
of mutating one object and finding out this object was
also reference through an other name you expected to remain
the same or finding out this object was also in a list you
expected to remain stable etc.

-- 
Antoon Pardon



More information about the Python-list mailing list