[Python-ideas] Quick idea: defining variables from functions that take the variable name
Sjoerd Job Postmus
sjoerdjob at sjoerdjob.com
Wed Jun 1 12:10:22 EDT 2016
> On 1 Jun 2016, at 17:59, Steven D'Aprano <steve at pearwood.info> wrote:
>
>> On Tue, May 31, 2016 at 10:35:01AM -0700, David Mertz wrote:
>>
>> For things like namedtuple that need more arguments, you'd need to use
>> functools.partial to create the single argument callable to match the
>> syntax.
>
> As far as I am concerned, limiting it to single-argument functions
> cripples this proposal to the point that it is of no interest.
>
> So far I've seen exactly four real-world use-cases, plus potentially
> Django. Only supporting a single name makes this useless for two of
> those use-cases, and I predict all of the Django examples[1]. Using
> partial is *more work than the status quo* which means nobody in their
> right mind is going to use it.
>
>
>
> # (1) status quo
> Record = namedtuple("Record", fields)
>
>
> # (2a) my suggestion
> Record -> namedtuple(fields)
>
> # (2b) or if you insist
> def Record = namedtuple(fields)
>
>
> # (3) if it only supports a single argument
> from functools import partial
> Record -> partial(namedtuple, field_names=fields)()
>
>
> That is significantly more annoying than the status quo. But it gets
> worse! Remember that partial() binds positional arguments from the left,
> which is the wrong side for what we need. Fortunately namedtuple
> supports keyword arguments, but what about those that don't?
>
> For the sake of the exercise, let's pretend that namedtuple doesn't
> support keyword arguments, just to get an idea of how to solve it:
>
> Record -> partial(lambda fields, name: namedtuple(name, fields), fields)()
>
> And let's just hope nobody wants to call namedtuple with the other
> arguments, verbose or rename.
>
> It is easy to wave your hands and say "just use partial", but not so
> easy to *actually do so*.
I'm working under the assumption that "eventually" the functions get reworked so as to return a 1-argument function.
So (using the -> syntax)
x -> Symbol
Point -> namedtuple_wrapper(['x', 'y'])
Becomes
x = Symbol('x')
Point = namedtuple_wrapper(['x', 'y'])('Point')
Adding the name as a first argument looks even more hacky to me, to be honest.
As for
x, y, z -> expr
Should raise a syntax-error for all I care. Unless everybody agrees that it should call the naming creator 3 times? I would find it confusing, to be honest.
So it would be
identifier -> expression
Not
identifier_list -> expression
More information about the Python-ideas
mailing list