default behavior
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Sat Jul 31 05:55:22 EDT 2010
On Sat, 31 Jul 2010 01:02:47 -0400, wheres pythonmonks wrote:
>> Hint -- what does [].append(1) return?
>>
>>
> Again, apologies from a Python beginner. It sure seems like one has to
> do gymnastics to get good behavior out of the core-python:
>
> Here's my proposed fix:
>
> m['key'] = (lambda x: x.append(1) or x)(m.get('key',[]))
>
> Yuck!
Yuk is right. What's wrong with the simple, straightforward solution?
L = m.get('key', [])
L.append(1)
m['key'] = L
Not everything needs to be a one-liner. But if you insist on making it a
one-liner, that's what setdefault and defaultdict are for.
> So I guess I'll use defaultdict with upcasts to dict as needed.
You keep using that term "upcast". I have no idea what you think it
means, so I have no idea whether or not Python does it. Perhaps you
should explain what you think "upcasting" is.
> On a side note: does up-casting always work that way with shared
> (common) data from derived to base? (I mean if the data is part of
> base's interface, will b = base(child) yield a new base object that
> shares data with the child?)
Of course not. It depends on the implementation of the class.
--
Steven
More information about the Python-list
mailing list