[Python-ideas] Quick idea: defining variables from functions that take the variable name
Steven D'Aprano
steve at pearwood.info
Wed Jun 8 11:19:37 EDT 2016
On Tue, Jun 07, 2016 at 11:17:26PM -0400, Eric V. Smith wrote:
> I think we might need some helpers, and a slight change to the
> specifics. I'd have:
>
> @binding_method
> x = obj
>
> result in:
> x = binding_method('x', obj)
That's a bit more promising.
Disadvantage:
- what was one line is now two;
- confusing to pass more than a single argument (plus the implicit name)
to the function;
- fails the principle "things that look similar should be similar".
Status quo:
Record = namedtuple('Record', fields)
would become:
@namedtuple
Record = fields
which doesn't look awful. I'm sad that it needs two lines.
But what if you want to pass more than one argument?
@namedtuple
Record = fields, True
That will be equivalent to
namedtuple('Record', (fields, True))
which is not what is wanted. And it gets worse if you use a keyword
argument:
Record = fields, verbose=True
I don't really like the way the @ syntax is being used for two
completely different things.
@function
def spam(): ...
does one thing, but
@function
spam = ...
does a completely different and unrelated thing. I'm not saying that @
cannot be used for anything but decorators, but I think it is confusing
to use something which looks so close to decorator syntax for something
that is nothing like a decorator.
> The question for me is: do we want to have something that tells the
> compiler that "binding_method" or "namedtuple" above are special, or is
> this just what the compiler does for all uses of what looks like a
> decorated assignment statement?
I'm surprised you ask that question :-) What does the Zen say about
special cases?
I don't think it is desirable to have developers have to go cap in hand
to the core devs and say "Please sir, I have a function that needs to
know its name, can you please add it to the privileged list of special
functions that work with @ please?"
*wink*
It should either work for any name after the @ or not at all. Hard
coding support for just namedtuple would be bad.
--
Steve
More information about the Python-ideas
mailing list