specifying constants for a function (WAS: generator expressions: performance anomaly?)

Steven Bethard steven.bethard at gmail.com
Sat Jan 22 02:57:58 CET 2005


I wrote:
 > If you really want locals that don't contribute to arguments, I'd be
 > much happier with something like a decorator, e.g.[1]:
 >
 > @with_consts(i=1, deftime=time.ctime())
 > def foo(x, y=123, *args, **kw):
 >    return x*y, kw.get('which_time')=='now' and time.ctime() or deftime
 >
 > Then you don't have to mix parameter declarations with locals
 > definitions.
 >
 > Steve
 >
 > [1] I have no idea how implementable such a decorator would be.  I'd
 > just like to see function constants declared separate from arguments
 > since they mean such different things.

I played around with this, and I think it's basically implementable:

py> import new
py> class with_consts(object):
...     def __init__(self, **consts):
...         self.consts = consts
...     def __call__(self, func):
...         return new.function(func.func_code,
...                             dict(globals(), **self.consts))
...
py> @with_consts(y=123)
... def f(x):
...     return x*y, str
...
py> f(2)
(246, <type 'str'>)

I just update the function globals with the keywords passed to the 
decorator.  The only problem is that updates to globals() aren't 
reflected in the function's globals:

py> str = 5
py> f(2)
(246, <type 'str'>)

Steve



More information about the Python-list mailing list