[Python-ideas] Statement local functions and classes (aka PEP 3150 is dead, say 'Hi!' to PEP 403)

Terry Reedy tjreedy at udel.edu
Fri Oct 14 17:31:06 CEST 2011


On 10/12/2011 8:22 PM, Nick Coghlan wrote:

> Basic Examples
> ==============
>
> Before diving into the long history of this problem and the detailed
> rationale for this specific proposed solution, here are a few simple
> examples of the kind of code it is designed to simplify.
>
> As a trivial example, weakref callbacks could be defined as follows::
>
>      :x = weakref.ref(obj, @)
>      def report_destruction(obj):
>          print("{} is being destroyed".format(obj))

You have already revised the wretchedness of the above syntax, but...

> This contrasts with the current repetitive "out of order" syntax for this
> operation::
>      def report_destruction(obj):
>          print("{} is being destroyed".format(obj))
>      x = weakref.ref(obj, report_destruction)

To me, 'define it, use it' is *in the proper order*. That you feel you 
have to masquerade an opinion or stylistic preference as a fact does not 
say much for the proposal.

For this trivial example, the following works:

x = weakref.ref(obj, lamdda x: print("{} is being destroyed".format(x)))

Let call_wrapper(g) be a decorator that wraps f with a call to g. In 
other words, call_wrapper(g)(f) == g(f). Perhaps just

def call_wrapper(g):
     def _(f):
         return g(f)
     return _

Then I believe the following, or something close, would work, in the 
sense that 'x' would end up being bound to the same thing as above, with 
no need for the throwaway one-use name:

@call_wrapper(functools.partial(weakref.ref, obj))
def x(obj):
     print("{} is being destroyed".format(obj))

If one prefers, functool.partial could be avoided with

def call_arg_wrap(g,arg):
     def _(f):
         return(g(arg,f)
     return _

@call_arg_wrap(weakref.ref, obj)
def x(obj):
     print("{} is being destroyed".format(obj))

-- 
Terry Jan Reedy




More information about the Python-ideas mailing list