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

Steven D'Aprano steve at pearwood.info
Tue May 31 10:04:16 EDT 2016

On Wed, Jun 01, 2016 at 01:02:57AM +1200, Greg Ewing wrote:
> >On 31 May 2016 at 04:08, Steven D'Aprano <steve at pearwood.info> wrote:
> >
> >>T -> TypeVar()
> >>x -> Symbol()
> >>T -> type(bases, ns)
> >>Record -> namedtuple(fields)
> The arrow seems back to front. It should point towards
> the name being assigned.

See my response to Stephen, but in a nutshell, no, we can't use <- 
because that's already legal for (less than) (unary minus).

Besides, the concepts I'm hinting at with -> are:

(1) "x becomes the value of the right hand side"

(2) "copy the name 'x' over to the right hand side"

>    T <- TypeVar()
>    x <- Symbol()
>    T <- type(bases, ns)
>    Record <- namedtuple(fields)
> Also, if the RHS is going to be called as part of
> the <- operation, shouldn't the first two just be
>    T <- TypeVar
>    x <- Symbol

No, because in the general case they might require more than 
one argument. Besides, I want to make it clear that the right hand side 
is being called. And I don't want to make the same mistake as decorator 

I'm not saying that decorator syntax is bad (it's been really 
successful!) but the choice to leave off the parens does make things a 
bit more complicated in some cases. E.g. if your decorator wants to take 
extra arguments, you have to write a decorator factory:

def factory(args):
    def decorator(func):
        def inner(*args, **kwargs):
        return inner
    return decorator

def spam(): ...

That's not awful, but it does lead to a trap: what if you make the 
args optional? Then you can leave them out when calling the factory:

def spam(): ...

but in practice that tends to be a bug magnet, because people 
invariably forget the parens. And *that* leads to spam being bound to 
the decorator itself, which is wrong, but you don't find out until you 
actually call spam.

I don't think this suggested syntax will be used as often as decorators, 
so I don't think it's worth the risk of complicating matters by making 
the parens optional. Keep them explicit and then you never need to worry 
about whether they are needed or not, they're always needed.

> The main drawback is that '<-' doesn't suggest in any
> way what's going on.

Well, apart from the languages and pseudo-code that already uses <- as 
an assignment operator :-)

> An alternative might be
>    def x = Symbol
> since 'def' has the precedent of attaching the name
> being bound to the object being created.

I never thought of it like that before.

To me, I don't think def is a good match because def doesn't have a left 
and right hand side. Assignment does. I know that *technically* def is 
an assignment (a name binding) but it doesn't look like one. It looks 
like a definition or declaration.


More information about the Python-ideas mailing list