[Python-ideas] Quick idea: defining variables from functions that take the variable name
Steven D'Aprano
steve at pearwood.info
Fri Jun 3 02:05:54 EDT 2016
On Thu, Jun 02, 2016 at 09:01:03AM +1200, Greg Ewing wrote:
> Steven D'Aprano wrote:
> >I'm not proposing any changes to namedtuple at all -- its others who
> >want to change it to take just a single argument and have an wrapper
> >function to specify the field names. I'm against that rather strongly.
>
> I don't think this would be creating TMWTDI.
I'm not objecting to it because it creates more than one way to do it.
I'm objecting to it because it needlessly doubles the number of
callables needed. Instead of there being one namedtuple function, you
need two: a single parameter version, and a wrapper that performs
whatever magic is needed to crowbar the multiple parameter version into
the constraint of a single parameter version.
For example, we have int(), which takes either one or two arguments:
int("23")
=> returns 23
int("23", 16)
=> returns 35
We don't have int, and int_wrapper:
# Python doesn't do this.
int_wrapper(16)("23")
=> returns 35
> Given the
> proposed feature, and a suitable helper, then
>
> def Foo as NamedTuple('x', 'y', 'z')
>
> would become the *obvious* way to define a named tuple
> type.
I'm not really sure that the difference between namedtuple and
NamedTuple is obvious, and I'm confident that the subtle difference
between them will be a bug-magnet. But maybe we could solve that
somehow.
In any case, I agree that the new syntax would become the One Obvious
Way. There's no real semantic difference between:
def Record as namedtuple('x y z')
Record -> namedtuple('x y z')
and while I'm not a big fan of the def ... as syntax, I could live with
it. One thing I dislike is that it reverses the usual sense of "as":
import module as foo # module is bound to name "foo"
with cm() as foo # context manager is bound to name "foo"
try:... except E as foo # exception is bound to name "foo"
All other uses have "as foo" set the name. But you have:
def foo as thing_that_is_called
which backwards is, as speaks Yoda.
But there is a rather big semantic difference once you insist that the
thing that is called must only accept a single argument.
--
Steve
More information about the Python-ideas
mailing list