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

Paul Moore p.f.moore at gmail.com
Tue May 31 11:46:51 EDT 2016


On 31 May 2016 at 16:08, Steven D'Aprano <steve at pearwood.info> wrote:
> On Tue, May 31, 2016 at 03:39:14PM +0100, Paul Moore wrote:
>
>> [I still prefer "call the RHS with the name of the LHS as the
>> argument" over "inject the name of the LHS as the first argument of
>> the call present on the RHS", btw -
>
> Do I understand that you think that the RHS should be limited to
> callables that take a single argument only?

Yes. Or more specifically, expressions that evaluate to a callable.
Because as you said in your original post, once you start allowing
injection into anything more complicated than a "simple call" the
whole thing gets messy. It's possible you could somehow restrict
what's allowed, but not easy - IIRC, the complications around what was
originally allowed in the position of a decorator were similar.

Also, needing to have the "wrong" number of arguments on the RHS seems
like it would lead to confusion:

    T => TypeVar()
    x => sympy.Symbol()
    cls => type(bases, ns)
    Record => nametuple(fields)

Compare the calls on the RHS to the documentation. It'd probably also
play havoc with IDEs that do signature introspection.

> So far we have four real use-cases:
>
> T = TypeVar('T')
> x = sympy.Symbol('x')
> cls = type('cls', bases, ns)
> Record = nametuple('Record', fields)
>
> You would only support the first two cases and leave the others with the
> status quo? That seems like a strange restriction to make. What problem
> do you think the other two use-cases would cause that the first two
> don't?

The idea was that the second pair can easily be handled using
functools.partial. So there's no loss of functionality, just a (small)
inconvenience. Having said that, I've just checked functools.partial,
and it doesn't appear to allow for inserting an argument at the
*start* of the argument list. Bah. But you could still do

def mktype(bases, ns): return lambda cls: type(cls, bases, ns)
def mknamedtuple(fields) return lambda name: namedtuple(name, fields)

cls => mktype(bases, ns)
Record => mknamedtuple(fields)

... and if this were a language feature, there's nothing stopping
mknamedtuple being added to the collections module (and mktype
somewhere, maybe operator).

But conceded, it's a limitation. My feeling is that the benefit in
terms of simpler semantics is worth it, but I can see your POV as
well.

Paul


More information about the Python-ideas mailing list