Daniel <[EMAIL PROTECTED]> wrote: > Alex Martelli wrote: > > What about: > > > > c = compile(thestring, thestring, '<eval>') > > > > cc = new.code( ...all args from c's attributes, except the 5th > > one, constants, which should instead be: > > decimalize(c.co_consts)...) > > Wow, what an elegant solution! I had no hope that it would be this
Heh, funny, I was originally parsing your response as ironic, because _I_ don't think of this as elegant -- too boilerplatey (as the expansion I showed right after dispays!)... took me a sec to see you really mean it!-) > simple. I always wondered what compile() was useful for and now I know > at least one thing. I'll try it out tomorrow. Thanks a lot Alex! You're welcome! And, compile is also useful for many other things, such as any situation where you may need to run eval multiple times on the same string of source code (typically on multiple distinct dicts/namespaces): compile the source once, then in the loop eval the code object (bytecode) rather than the source -- that saves time. Also, you may do introspection on the code object -- for example, I show in the Nutshell's 2nd ed how this lets you perform a "safe eval" -- a way to let the user specify any Python "literal" without risking a malicious user running arbitrary code (essentially, you refuse to eval the code object if its co_names isn't empty -- or, you might let said co_names possibly contain just a few names you deem "safe", such as, say, 'sin', 'cos', 'tan', which you can get into your namespace from the math module). Such introspection on names may also allow some further optimization, particularly in the repeated-execution case, if there are "well-known names" that you're able to compute "just in time" (nowadays you can also use a special mapping to "only compute at need" the values for the names that are actually needed). Beyond which, we get into the realm of byecode hacks...!-) Alex -- http://mail.python.org/mailman/listinfo/python-list