[Python-ideas] Quick idea: defining variables from functions that take the variable name
steve at pearwood.info
Mon May 30 23:08:10 EDT 2016
On Mon, May 30, 2016 at 06:16:26PM -0700, Guido van Rossum wrote:
> T = TypeVar('T')
> x = Symbol('x')
> I'm sure this is not a new idea, but so far I've always thought that
> this is pretty esoteric and the approach here is good enough. But
> maybe we can actually do better, and whatever solution we come up with
> might also be useful for extracting attributes from an object or
> values from a mapping?
This comes up a lot and it would be nice to clean it up.
T = type('T', bases, ns)
Record = namedtuple('Record', fields)
It came up in the discussion on dict unpacking:
a, b, c = **dict # unpacks keys 'a', 'b', 'c'
which was rejected as too magical. But maybe it will seem less magical
if we have a special assignment operator that takes the left hand symbol(s)
and copies them to the right?
How do you feel about an arrow operator?
T -> TypeVar()
x -> Symbol()
T -> type(bases, ns)
Record -> namedtuple(fields)
name [, name, ...] -> callable(...)
where "callable" is some expression, e.g. a name, a dot lookup, etc.
name -> sympy.Symbol()
The easy case
All assignment targets are plain names.
The arrow operator takes the names, turns them into strings, and passes
them to the callable on the right as a tuple of strings, given as the first
Since the most common case will be a single target, I think it is worth
while to treat it as a special case and pass just a string:
T -> Type() # like Type('T')
a, b, c -> Spam(arg) # like Spam(('a', 'b', 'c'), arg)
The callable being called doesn't need to know or care whether it is
being called with the -> or = assignment. It just receives the name(s)
as the first argument.
This will mean that callables that take the name as (say) the second
argument cannot be used with this syntax.
Using the arrow operator with arbitrary expressions on the
right will be a SyntaxError:
x -> y + 1
my_name -> spam*f()
my_name -> f() or g()
I reject that third example as it is unclear whether both f and g, or
only f, get the name as first argument.
But this is allowed:
my_name -> f(g()) # like f('my_name', g())
If f isn't *actually* a callable, you get a runtime TypeError as usual.
The hard case
Assignment target(s) is not a plain name.
spam.eggs().attr -> Symbol()
I'm going to take the cowards way out and just say "we don't allow
More information about the Python-ideas