statements in control structures (Re: Conditional Expressions don't solve the problem)

Rich Harkins rharkins at thinkronize.com
Thu Oct 18 21:53:01 CEST 2001


Neither of these will do the trick nicely because in order to actually
modify the calling context one must work back through the stack backtraces.
For example, let's use the let function proposed:

def let(l,v):
	l[0]=v
	return l[0]

a=5
let([a],2)
print a

This prints 5 because let only modifies the first element of l and since the
variable "a" does not reside in the arguments (only its referenced object
does) the list gets changed but "a" goes merrily on.  You could say:

def let(d,name,v):
	l[name]=v
	return v

a=5
let(locals(),'a',2)

... but that is pretty ugly not to mention hacky.  Another hacky form of
this is:

import sys
def let(name,v):
	try:
		raise Exception
	except:
		t,v,tb=sys.exc_info()
		tb.tb_frame.f_back.f_locals[name]=v
		del t,v,tb
	return v

let('a',5)
print a

That works but it too is extremely ugly, unlikely to work in all conditions,
and would perform poorly.  So unless Python will almost certainly have to
grow a let extension if this effect is desired.

Rich


> -----Original Message-----
> From: python-list-admin at python.org
> [mailto:python-list-admin at python.org]On Behalf Of Christopher A. Craig
> Sent: Thursday, October 18, 2001 10:23 AM
> To: Anders J. Munch
> Cc: python-list at python.org
> Subject: Re: statements in control structures (Re: Conditional
> Expressions don't solve the problem)
>
>
> "Anders J. Munch" <andersjm at dancontrol.dk> writes:
>
> > Here's an additional alternative:
> >
> > Use a function-like form let to perform assignment within expression.
> >   let(X,Y)
> > has the effect of doing
> >   X = Y
> > and returning the assigned object.
>
> I had thought about doing this earlier.  You could do this now
> with a little
> ugly syntax:
>
> def let(a, b):
>   a[0] = b
>   return a[0]
>
> while let([a], get_next()):
>   process(x)
>
>
> The problem being that you have to pass the variable as an element in a
> mutable structure in order to modify it.  The problem with your proposal
> being that you don't (and it would be the only function where you don't).
>
> --
> Christopher A. Craig <com-nospam at ccraig.org>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>





More information about the Python-list mailing list