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

Steven D'Aprano steve at pearwood.info
Tue May 31 09:37:17 EDT 2016

On Tue, May 31, 2016 at 03:01:48PM +0200, Sven R. Kunze wrote:
> And here we go again. Sorry for posting unfinished stuff:
> On 31.05.2016 11:05, Paul Moore wrote:
> >If this was simply about type definitions, I'd agree. But I thought
> >the point of Guido's post was that having seen two examples (TypeVar
> >and Symbol) is there a more general approach that might cover these
> >two cases as well as others? So just looking at the problem in terms
> >of stub files isn't really the point here.
> >
> I don't know why this needs special syntax anyway. Maybe, somebody could 
> explain.

Any time you have an object that needs to know its own name, you have to 
provide it as a string, AND as an assignment target:

    T = TypeVar('T')
    x = sympy.Symbol('x')
    myclass = namedtuple("myclass", fields)
    klass = type('klass', bases, ns)

The only exceptions are when you can use compiler magic do to it for 
you. We don't have to write these:

    math = import math

    func = def func(arg): ...

    MyClass = class MyClass(Parent): ...

because the compiler does it for us. Likewise we have @ decorator syntax 
to avoid writing the function name three times:

    def spam():

    spam = decorate(spam)

This solves the same problem for ordinary assignment: how to get the 
name or names on the left hand side over to the right hand side without 
re-typing them as strings?

> Even Guido said it was just for procrastinating. So, I don't 
> give much weight to it.

This comes up from time to time. It was one of the motives for adding @ 
decorator syntax, so maybe its the right time for it now.

> Anyway, what's the difference between:
> a = <something>
> and
> def a = <something>
> ?
> Both evaluate RHS and assign the result to a name (if not already 
> defined, define the name)

The "def a = ..." is not my suggested syntax, so I can't tell you 
exactly what it will do, but *my* suggested syntax is:

name -> Function(args)

will be expanded to:

name = Function('name', args)

by the compiler. The "def a = ..." syntax will probably be similar. 
Somehow, in some fashion, the name "a" on the LHS will be passed as a 
string to something on the RHS.


More information about the Python-ideas mailing list