Namedtuples: some unexpected inconveniences

Deborah Swanson python at deborahswanson.net
Sun Apr 16 13:19:58 EDT 2017


Peter Otten wrote, on Saturday, April 15, 2017 12:44 AM
> 
> Deborah Swanson wrote:
> 
> > I know it's your "ugly" answer, but can I ask what the '**' in
> > 
> > fix = {label: max(values, key=len)}
> > group[:] = [record._replace(**fix) for record in group]
> > 
> > means?
> 
> d = {"a": 1, "b": 2}
> f(**d)
> 
> is equivalent to
> 
> f(a=1, b=2)

Thisis perfect Peter, thank you very much. Now I can understand why your
"ugly" fix works, instead of just seeing in the degugger that
mysteriously it does somehow work.

> so ** is a means to call a function with keyword arguments when you
want to 
> decide about the *names* at runtime. Example:
> 
> >>> def f(a=1, b=2):
> ...     print("a =", a)
> ...     print("b =", b)
> ...     print()
> ... 
> >>> for d in [{"a": 10}, {"b": 42}, {"a": 100, "b": 200}]:
> ...     f(**d)
> ... 
> a = 10
> b = 2
> 
> a = 1
> b = 42
> 
> a = 100
> b = 200

Looks like a very handy type of "kwarg" to know about. It would be nice
if the doc writers weren't so mysterious about what can be used for
"kwargs", or they explained somewhere what the possible "kwargs" can be.
Even in the one index entry for "kwargs", all they say about what it is,
is "A dict of keyword arguments values", and that only applies to the
Signature object. I've see "kwargs" in articles other than for
namedtuples, always mysteriously, with no details on what the
possibilities are and how to use them. (Makes me wonder where you
learned all this ... ;)
 
> Starting from a namedtuple `record`
> 
> record._replace(Location="elswhere")
> 
> creates a new namedtuple with the Location attribute changed to
"elsewhere", 
> and the slice [:] on the left causes all items in the `groups` list to
be 
> replaced with new namedtuples,
> 
> group[:] = [record._replace(Location="elsewhere") for record in group]
> 
> is basically the same as
> 
> tmp = group.copy()
> group.clear()
> for record in tmp:
>     group.append(record_replace(Location="elsewhere"))
> 
> To support not just Location, but also Kind and Notes we need 
> the double asterisk.

I saw this in the debugger, but again didn't really understand why it
was working. So this really clears it up, and I plan to look at it in
the debugger again to be sure I understand it all. Thanks very much.



More information about the Python-list mailing list