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

Eric V. Smith eric at trueblade.com
Tue Jun 7 23:17:26 EDT 2016


On 6/7/2016 10:40 PM, Steven D'Aprano wrote:
> On Tue, Jun 07, 2016 at 12:53:23AM +0200, M.-A. Lemburg wrote:
>> On 07.06.2016 00:32, Barry Warsaw wrote:
>>> On Jun 01, 2016, at 03:53 PM, M.-A. Lemburg wrote:
>>>
>>>> This could be done via a decorator:
>>>>
>>>>    @recordbinding
>>>>    x = obj
>>>>
>>>> to result in the compiler generating the following code:
>>>>
>>>>    x = obj
>>>>    obj.recordbinding('x', 2)
>
> I don't understand the purpose of the second argument, given as 2.
> Earlier you say that it's the line number. Why is that needed?
>
> I don't see how this actually solves the problem. Apply it to
> namedtuple:
>
> Record = namedtuple('Record', fields)
>
> If you naively try the decorator:
>
> @recordbinding
> Record = namedtuple(fields)
>
> that gets converted to:
>
> Record = namedtuple(fields)  # TypeError
> Record.recordbinding('Record')  # AttributeError

I think we might need some helpers, and a slight change to the 
specifics. I'd have:

@binding_method
x = obj

result in:
x = binding_method('x', obj)

Then you could just say:

@namedtuple
Point = 'x y z'

Which would become:

Point = namedtuple('Point', 'x y z')

(or equivalently in this case:
@namedtuple
Point = ['x', 'y', 'z']
)

As has been pointed out, it's possible a different signature would be 
needed (not sure about line numbers, but qualname seems desirable). In 
that case, "namedtuple" above might not be "collections.namedtuple", but 
some helper.

The question for me is: do we want to have something that tells the 
compiler that "binding_method" or "namedtuple" above are special, or is 
this just what the compiler does for all uses of what looks like a 
decorated assignment statement?

Eric.

> There's no point in calling a special method on the RHS object, as that
> requires the object to have been constructed before the method can be
> called. And that requires the name. So your recordbinding decorator gets
> called too late.
>
> Even if it worked, I strongly dislike that this turns a one-line
> expression into a two line statement.
>
> # Status quo:
> x = sympy.Symbol('x')
>
> # Becomes:
> @recordbinding
> x = sympy.Symbol()
>
> which doesn't seem like an improvement to me.
>
> [...]
>> This would work as well and indeed reads better, but you'd need
>> to have the compiler generate:
>>
>>       x = obj
>>       recordbinding(obj, 'x', 2)
>>
>> ie. pass in the object, the bound name and the line number
>> and recordbinding would then have to decide what to do with the
>> parameters.
>
> Again, this is called too late. Your namedtuple needs its name when it
> is constructed, it can't be constructed first and then the name injected
> in, even if recordbinding() knew where to inject the name.
>
>



More information about the Python-ideas mailing list