[Python-ideas] Short form for keyword arguments and dicts

Nick Coghlan ncoghlan at gmail.com
Sun Jun 23 03:26:22 CEST 2013


On 23 June 2013 06:07, Joshua Landau <joshua.landau.ws at gmail.com> wrote:
> On 22 June 2013 20:51, Anders Hovmöller <boxed at killingar.net> wrote:
>> Ok. Why? I'm not saying you're wrong, I just want to know what the reasons
>> are so I can understand why I was mistaken so I can forget about this idea
>> :P
>
> Does foo(=bar) not bug you?
> Really?

Indeed, any kind of "implied LHS" notation isn't going to happen in
the foreseeable future for Python.

That said, the repetitiveness of passing several local variables as
keyword arguments *is* mildly annoying.

A potential more fruitful avenue to explore may be to find a clean
notation for extracting a subset of keys (along with their values)
into a dictionary.

With current syntax, the original example can already be written as
something like this:

>>> def submap(original, *names):
...     return type(original)((name, original[name]) for name in names)
...
>>> a, b, c = 1, 2, 3
>>> submap(locals(), "a", "b", "c")
{'a': 1, 'b': 2, 'c': 3}
>>> f(**submap(locals(), "a", "b", "c"))
{'a': 1, 'b': 2, 'c': 3}
>>> from collections import OrderedDict
>>> o = OrderedDict.fromkeys((1, 2, 3, 4, 5))
>>> o
OrderedDict([(1, None), (2, None), (3, None), (4, None), (5, None)])
>>> submap(o, 1, 3, 5)
OrderedDict([(1, None), (3, None), (5, None)])

(There are also plenty of possible variants on that idea, including
making it a class method of the container, rather than deriving the
output type from the input type)

This is potentially worth pursuing, as Python currently only supports
"operator.itemgetter" and comprehensions/generator expressions as a
mechanism for retrieving multiple items from a container in a single
expression. A helper function in collections, or a new classmethod on
collections.Mapping aren't outside the realm of possibility.

For the question of "How do I enlist the compiler's help in ensuring a
string is an identifier?", you can actually already do that with a
simple helper class:

>>> class Identifiers:
...     def __getattr__(self, attr):
...         return attr
...
>>> ident = Identifiers()
>>> ident.a
'a'
>>> ident.b
'b'
>>> ident.c
'c'

Combining the two lets you write things like:

>>> submap(locals(), ident.a, ident.b, ident.c)
{'a': 1, 'b': 2, 'c': 3}

Personally, I'd like to see more exploration of what the language
*already supports* in this area, before we start talking about adding
dedicated syntax.

Cheers,
Nick.

--
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list