[Python-ideas] Quick idea: defining variables from functions that take the variable name
Steven D'Aprano
steve at pearwood.info
Wed Jun 1 11:59:09 EDT 2016
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*.
[1] On the basis that very few objects need to know *only* their name. I
expect that if Django uses this pattern, it will take a name plus at
least one more argument.
--
Steve
More information about the Python-ideas
mailing list