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

Joao S. O. Bueno jsbueno at python.org.br
Fri Jul 12 01:57:07 CEST 2013


I don't know if what I miss most is the samething the OP is asking for -
but the idea of re-using a value retrieved in an expression in the
same expression - without the need
to assign to a temporary variable.

Like in:
  value = expensive_function(b)  if expensive_function(b) else default_value

(of course this is a trivial example - but nonetheless it would require an
extra "if" statement to avoid the double call)

Anyway, the proposed syntax in the O.P. would not suffice for this case.

On 11 July 2013 18:41, Andrew Barnert <abarnert at yahoo.com> wrote:
> 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
>
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>


More information about the Python-ideas mailing list