[Python-ideas] Reference variable in assignment: x = foo(?)

Andrew Barnert abarnert at yahoo.com
Thu Jul 11 23:41:22 CEST 2013


On Jul 11, 2013, at 14:07, Corey Sarsfield <subbarker at gmail.com> wrote:

> I came up with the idea after having some code on dicts that looked like:
> 
> a[b][c] = foo(a[b][c]) 
> 
> So in this case there are twice as many look-ups going on as there need to be, even if a[b][c] were to be pulled out into x.  
> 
> If I were to do:
> 
> a[b][c] += 1
> 
> Would it be doing the lookups twice behind the scenes?

Effectively, the best it could possibly do is something like this:

    tmp = a[b]
tmp,__setitem__('c', tmp.__getitem__('c').__iadd__(1))

So yes, there are two lookups.

But if a[b] is a dict... Who cares? The lookup is a hash--which is cached after the first one--plus indexing into an array. 


> 
> 
> On Thu, Jul 11, 2013 at 4:00 PM, R. Michael Weylandt <michael.weylandt at gmail.com> wrote:
>> On Thu, Jul 11, 2013 at 3:39 PM, Corey Sarsfield <subbarker at gmail.com> wrote:
>> > I've always found +=, -= and the like to be handy, but I had hoped like so
>> > many other things in python there would be a generic form of this
>> > functionality.
>> >
>> > x += 5 could be expressed as x = ? + 5 perhaps.
>> >
>> >
>> 
>> Can you flesh this out a bit further? Isn't x += 5 <--> x = x + 5
>> already defined unless a class specifically does something funny with
>> __iadd__?
>> 
>> Cheers,
>> Michael
> 
> 
> 
> -- 
> Corey Sarsfield
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130711/90f804d6/attachment-0001.html>


More information about the Python-ideas mailing list