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

Paul Moore p.f.moore at gmail.com
Wed Jun 1 12:33:19 EDT 2016


On 1 June 2016 at 17:14, Steven D'Aprano <steve at pearwood.info> wrote:
> You should consider how your suggestion will work with the existing
> use-cases already shown.
>
> We've got two dead-simple use-cases to consider. If this proposal makes
> those use-cases harder than the status quo, then this proposal is dead
> in the water. Nobody is going to use it.

There's almost no room for improvement in those two use cases, and yet
people still like the idea of "not repeating the name". I think (but
don't know for certain) that there are some users who would accept a
cost of a few extra characters to avoid the duplication.

> # Status quo.
> T = Typevar('T')
> x = sympy.Symbol('x')
>
> # My proposal.
> T -> Typevar()
> x -> sympy.Symbol()
>
>
> # Your proposal.
> def T as (lambda: Typevar)()
> def x as (lambda: sympy.Symbol)()

That's hardly fair. The two examples you quote are the ones that
really *do* work with the "one-argument function" restriction:

def T as Typevar
def x as sympy.Symbol

If you want to knock down the alternative proposal, you should use
namedtuple or type. But for those, the people arguing for them are
assuming (for better or worse) that additional helpers with a
signature compatible with the new syntax would be added to the stdlib
at the same time as the new syntax.

> You specify that the expression on the right must return a function that
> takes one variable, so you cannot use Typevar or Symbol directly. You
> have to call a function that returns the function you actually want.
>
> Syntactic sugar is supposed to make things easier, not harder.

The biggest problem I have with your proposal is how it would extend
to more complex cases (or probably more realistically, how the
language definition would disallow cases that can't be handled).

Can you give the actual syntax of your proposal, in the form used in
the Python language reference? The best I can come up with is

IDENTIFIER '->' CALL

but CALL (see https://docs.python.org/3/reference/expressions.html#grammar-token-call)
allows the form

    function(x for x in something)

and you can't inject a name at the front of that. So I guess you'd
have to split CALL into two parts, and only allow one of them here?

Paul


More information about the Python-ideas mailing list