No "side effect" assignment!

Paul Paterson paulpaterson at users.sourceforge.net
Fri Sep 19 01:24:21 EDT 2003


"Martin Maney" <maney at pobox.com> wrote in message
news:bkbfh1$8il$3 at wheel2.two14.net...
> Sean Ross <sross at connectmail.carleton.ca> wrote:
> > If you must use assignments in expressions, you might find the following
> > recipes useful:
> > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/202234
>
> Did I forget about this one or is it in fact new?  It is, as the author
> says, an ugly hack at the implementation level, but that seems to be
> its only drawback.

I think that the other drawback is that it only works at the top level of a
module. If you are inside a function or method then the locals() (f_locals)
dictionary is still writeable but it has no effect on the namespace it
represents.

So ...

import sys
def set(**kw):
    assert len(kw)==1

    a = sys._getframe(1)
    a.f_locals.update(kw)
    return kw.values()[0]

def main():
    A=range(10)

    while set(x=A.pop()):
        print x

main()

... prints 0,0,0,0,0,0 etc instead of what you want.

I guess you might call "a.f_locals.update(kw)" a no-(side)-effect assignment
;)

Paul






More information about the Python-list mailing list