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

Bengt Richter bokr at oz.net
Sat Jan 22 23:28:27 EST 2005


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>
 >>> import dis
 >>> dis.dis(foo)
   3           0 LOAD_CONST               1 ('Sat Jan 22 20:18:09 2005')
               3 STORE_FAST               3 (deftime)

   4           6 LOAD_CONST               2 ((2, 1))
               9 UNPACK_SEQUENCE          2
              12 STORE_FAST               2 (b)
              15 STORE_FAST               0 (a)

   5          18 LOAD_CONST               3 (3)
              21 STORE_FAST               1 (c)

   6          24 LOAD_CONST               4 (3.1415926535897931)
              27 STORE_FAST               4 (pi)

   7          30 LOAD_CONST               5 (<built-in function locals>)
              33 CALL_FUNCTION            0
              36 RETURN_VALUE
 >>> foo()
 {'a': 1, 'c': 3, 'pi': 3.1415926535897931, 'b': 2, 'deftime': 'Sat Jan 22 20:18:09 2005'}

Not vary tested as yet, but seems to work. I want to eliminate redundant constants if the
same name is assigned = __frompresets__ more than once. Right now I brute force generate
another constant.

Regards,
Bengt Richter



More information about the Python-list mailing list