[Python-ideas] Quick idea: defining variables from functions that take the variable name

Nick Coghlan ncoghlan at gmail.com
Tue Jun 7 19:09:28 EDT 2016


On 7 June 2016 at 15:51, Michael Selik <michael.selik at gmail.com> wrote:
> On Tue, Jun 7, 2016 at 4:13 PM Nick Coghlan <ncoghlan at gmail.com> wrote:
>>
>> As a possible guide to designing the signatures for binding
>> decorators, it's probably worth asking what would be needed to make:
>>
>>     @bindfunction
>>     f = lambda : None
>>
>> equivalent to:
>>
>>     def f(): pass
>>
>> Since the interpreter already sets __module__ and __globals__
>> correctly on lambda functions, the main considerations would be to get
>> f.__name__ and f.__qualname__ set correctly, which means just the
>> immediate target would be insufficient - you'd also want the scope
>> naming information that gets included in __qualname__, but is omitted
>> from __name__.
>
>
> The ``bindfunction`` function could look up the __module__ and use that to
> assign the __qualname__. Would that satisfy?

Not really, due to class and function nesting:

    >>> class A:
    ...     class B:
    ...        def f(self):
    ...             def g(): pass
    ...             return g
    ...
    >>> A.B().f.__qualname__
    'A.B.f'
    >>> A.B().f().__qualname__
    'A.B.f.<locals>.g'

That's why I brought it up as a design problem worth considering -
it's *very* easy to inadvertently design namebinding feature that only
do the right thing at module scope, and misbehave at class and
function scope.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list