[Python-ideas] Specifying constants for functions
Serhiy Storchaka
storchaka at gmail.com
Tue Oct 27 14:01:32 EDT 2015
On 27.10.15 19:45, Serhiy Storchaka wrote:
> There is known trick to optimize a function:
>
> def foo(x, y=0, len=len, pack=struct.pack, maxsize=1<<BPF):
> ...
>
> It has a side effect: change function's signature. Would be nice to have
> a way to set function's local variables at creation time without
> affecting a signature.
>
> Possible syntax (I'm not sure what is better):
>
> 1. Similar to "global" and "nonlocal" declarations with optional
> initializer.
>
> def foo(x, y=0):
> const len
> const pack=struct.pack, maxsize=1<<BPF
> ...
>
> 2. Same as 1, but using "as" instead of "=".
>
> def foo(x, y=0):
> uses len, struct.pack as pack
> uses 1<<BPF as maxsize
> ...
>
> 3. Declaration is moved to function header. The keyword "given" is
> inspired by PEP 3150.
>
> def foo(x, y=0) given len=len, pack=struct.pack, maxsize=1<<BPF:
> ...
>
> 4. Declaration is moved out of the function. The advantage is that bound
> names can be used to evaluate default values for actual parameters (it
> is useful to implement sentinel default value), and all expression are
> evaluated in natural order.
>
> using len, struct.pack as pack, 1<<BPF as maxsize:
> def foo(x, y=0):
> ...
>
> 5. The least wordy syntax. No new keyword needed.
>
> def foo(x, y=0; len=len, pack=struct.pack, maxsize=1<<BPF):
> ...
>
> All above examples would be roughly equivalent to the following code:
>
> def create(len=len, pack=struct.pack, maxsize=1<<BPF):
> def foo(x, y=0):
> ...
> return foo
> tmp = create()
> def foo(x, y=0):
> pass
> update_wrapper(tmp, foo)
> foo = tmp
> del create, tmp
>
> This feature is rather ideologically opposite to Victor's approach.
Oh, only after sending my message I had read Scott's message about the
asconstants decorator, that does just this optimization [1]. With this
decorator above example can be written as:
from codetransformer.transformers import asconstants
@asconstants(len=len, pack=struct.pack, maxsize=1<<BPF)
def foo(x, y=0):
...
But it depends on bytecode implementation details. I wondering if it is
worth to support this feature by syntax.
[1] http://permalink.gmane.org/gmane.comp.python.ideas/36958
More information about the Python-ideas
mailing list