[Python-ideas] Quick idea: defining variables from functions that take the variable name
Steven D'Aprano
steve at pearwood.info
Tue Jun 7 22:40:56 EDT 2016
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
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.
--
Steve
More information about the Python-ideas
mailing list