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

Steven Bethard steven.bethard at gmail.com
Sun Jan 23 15:14:10 EST 2005


Bengt Richter wrote:
> On Sat, 22 Jan 2005 16:22:33 +1000, Nick Coghlan <ncoghlan at iinet.net.au> wrote:
> 
> 
>>Steven Bethard wrote:
>>
>>>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:
>>
>>Raymond's constant binding decorator is probably a good model for how to do it:
>>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940
>>
> 
> 
> I thought so too. I modified it to accept **presets as a keyword argument
> and generate constants and assignments from its values matching assignment names
> when the rhs was __frompresets__, e.g.,
> 
>  >>> from makeconstpre import make_constants as pre
>  >>> import time
>  >>> @pre(verbose=True, deftime=time.ctime(), a=1, b=2, c=3, pi=__import__('math').pi)
>  ... def foo():
>  ...     deftime = __frompresets__
>  ...     b, a = __frompresets__
>  ...     c = __frompresets__
>  ...     pi = __frompresets__
>  ...     return locals()
>  ...
>  __frompresets__ : deftime --> Sat Jan 22 20:18:09 2005
>  __frompresets__ : ('b', 'a') --> (2, 1)
>  __frompresets__ : c --> 3
>  __frompresets__ : pi --> 3.14159265359
>  locals --> <built-in function locals>

Hmm... Having to state
     deftime = __frompresets__
when you've already stated
     deftime=time.ctime()
seems a little redundant to me...

Steve



More information about the Python-list mailing list