[Python-ideas] Specifying constants for functions

Serhiy Storchaka storchaka at gmail.com
Tue Oct 27 13:45:37 EDT 2015

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 

     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):
     update_wrapper(tmp, foo)
     foo = tmp
     del create, tmp

This feature is rather ideologically opposite to Victor's approach.

More information about the Python-ideas mailing list