With or Using

Delaney, Timothy tdelaney at avaya.com
Sun Apr 29 21:48:53 EDT 2001


> > One thing I haven't seen yet is when you need to write
> >     a.b.c().d[4].e.f.g.h().i = 1
> >     a.b.c().d[4].e.f.g.h().j = 1
> >     a.b.c().d[4].e.f.g.h().k = 1
> > that you could just as well write
> >     temp = a.b.c().d[4].e.f.g.h()
> >     temp.i = 1
> >     temp.j = 1
> >     temp.k = 1
> > or (ugly!)
> >     for temp in a.b.c().d[4].e.f.g.h(),:
> >         temp.i = 1
> >         temp.j = 1
> >         temp.k = 1
> > i.e., store a reference to the same thing the long 
> expression gives you
> > in an easy-to-type place.
> >
> Of course, augmented assignment was made for situations where 
> you would like
> to avoid writing
> 
>     a.b.c().d[4].e.f.g.h().k = a.b.c().d[4].e.f.g.h().k + 1
> 
> allowing you instead to write
> 
>     a.b.c().d[4].e.f.g.h().k += 1

I am of course aware that the above is using silly made-up expressions, but
they raise an important point.

Both of the above may actually have different semantics. In each case you
have a large number of function calls (remember, each class attribute access
can be a function call ...). If any one of those calls returns a different
object to the previous invocation, the two verions may be semantically
different. In this case, binding to a temporary may be the wrong thing to do
(or at least less of the expression should be bound to the temporary).

If they are *not* semantically different however you can save quite a bit of
time by assigning to a temporary variable - if you don't, all of those
things need to be evaluated each time.

Tim Delaney




More information about the Python-list mailing list