Code evaluation at function definition execution time (was Re: Compile time evaluation (aka eliminating default argument hacks))

Carl Banks invalidemail at aerojockey.com
Thu Mar 10 18:09:51 EST 2005


Nick Coghlan wrote:
> Anyway, if others agree that the ability to execute a suite at def
exeuction
> time to preinitialise a function's locals without resorting to
bytecode hacks is
> worth having, finding a decent syntax is the next trick :)

Workarounds:

1. Just use a freaking global, especially if it's just a stateless
piece of data.  Give it a long decriptive name, make it all caps,
precede it with an underscore, and put a comment nearby saying that
it's only for use with a certain function.  If someone uses it for
another reason anyways, BFD, we're all adults here.  If you need more
speed, assign it a local alias.


2.

. def call_and_replace_with_result(func):
.     return func()
.
. @call_and_replace_with_result
. def function_with_predefined_locals():
.     x = initialize()
.     y = initialize()
.     def real_function(a,b,c):
.         use(x,y,a,b,c)
.     return real_function


I wouldn't use it, though, since a global variable is much more
readable and not much more dangerous.  I could, however, see myself
using the slightly more complicated descriptor such as this (for a
wholly different reason, though):

. def call_with_open_file(filename):
.     def descriptor(func):
.          flo = open(filename)
.          try: f(flo)
.          finally: f.close()
.          return None
.     return descriptor



-- 
CARL BANKS




More information about the Python-list mailing list