On Wed, 23 Mar 2005 06:21:30 +0100, Kay Schluehr <[EMAIL PROTECTED]> wrote:
>I think my proposal was more in mind of Rons modified exec than >Pythons lambda. > >When George proposed his unpacking behavoir for list-comps as a pack of >suggar: > >1. [x*y-z for (x,y,z=0) in (1,2,3), (4,5), (6,7,8)] > >I interpreted it in a subsequent posting in lambda fashion: > >2. [(lambda x,y,z=0:x*y-z)(*v) for v in (1,2,3), (4,5), (6,7,8)] Thank you Kay, All of this is really intersting and I'm learning a lot about the language through these discussions. The following is an experiment I did this morning. :-) I was surprised it worked as well as it did, although I don't think it should be used in any real production code. Not in it's present form anyway. The idea is to have a container class like a tuple for program code that can be moved around and used when needed. Very flexable, maybe if it could be done without the strings and the exec/eval() functions in it? Ron_Adam # codedo.py import types class code(tuple): """ Inline Code Storage Class name = code(('expression','expression',...)) varables = name.do([locals()],['invars'],'outvars') This is experimental. Warning: This is experimental! This class has not been tested. It also uses exec, and eval(), which can be a security risk. """ def do(self, *args ): if type(args[0]) == type({}): parentnames = args[0] else: parentnames = globals() if len(args)>1: argslist = args[1].split(',') else: argslist = args for a in argslist: if parentnames.has_key(a): exec a+'=parentnames[a]' for c in self: exec(c) return eval(args[-1]) # The last argument are the return varable(s). if __name__ == '__main__': """ Test it. This is only what works, not what doesn't. """ # Left to Right order. y=3 print code(('y=y*2','x=y**2')).do('x') # *** Define and use later! *** mybutton_action = code(('z=y*2','x=z**2','result=x+2')) y = 1 print mybutton_action.do('y','result') y = 10 print mybutton_action.do('y','result') y = 100 print mybutton_action.do('y','result') # Return multiple values. toxyz = code(('x*=2','y*=2','try:z\nexcept:z=0','z*=2')) x = 2 y = 3 #z = 4 a, b, c = toxyz.do('x,y,z') print a, b, c # 1. [x*y-z for (x,y,z=0) in (1,2,3), (4,5), (6,7,8)] print code(('r=[]','for x,y,z in [(1,2,3),(4,5,0),(7,8,9)]:r.append(x*y-z)')).do('r') # or... trailing comma needed here to make a uni-tuple. print code(('r=list([x*y-z for x,y,z in (1,2,3),(4,5,0),(7,8,9)])',)).do('r') # post process list before returning. print code(('r = [ x for x in range(1,11) ]','r=r*2')).do('r') # From within a function: # We need to pass locals() to so it can find the variables. def fn1(): x = 5 y = 10 lfunction = code(('z = x*2+y',)).do(locals(),'x,y','z') print lfunction fn1() -- http://mail.python.org/mailman/listinfo/python-list