[Python-ideas] Reference variable in assignment: x = foo(?)
Steven D'Aprano
steve at pearwood.info
Fri Jul 12 07:25:41 CEST 2013
On 12/07/13 07:07, Corey Sarsfield 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.
How do you reason that? You need two sets of lookups however you do it: first you call __getitem__ 'b' and 'c', then you call __setitem__. In the general case, you can't cache the reference 1) because that's not how references work in Python, and 2) even if it were, any of the __getitem__ or __setitem__ calls may have side-effects.
> If I were to do:
>
> a[b][c] += 1
>
> Would it be doing the lookups twice behind the scenes?
Easy enough to find out with a helper class:
class Test(list):
def __getitem__(self, attr):
print("Looking up item %s" % attr)
return super(Test, self).__getitem__(attr)
def __setitem__(self, attr, value):
print("Setting item %s to %r" % (attr, value))
return super(Test, self).__setitem__(attr, value)
instance = Test([1, 2, 3])
instance[1] = Test([4, 5, 6])
instance[1][2] += 100
print(instance)
--
Steven
More information about the Python-ideas
mailing list