Dictionary Comprehension

Paul Rubin phr-n2002a at nightsong.com
Tue Mar 19 17:16:26 EST 2002


Michael Hudson <mwh at python.net> writes:
> The "Parade of the PEPs" says:
> 
>   PEP 274 - Dict Comprehensions - Warsaw
> 
>     If we were to adopt dict comprehensions, this PEP says everything
>     that needs to be said. But I don't even want to think about this
>     for Python 2.3; I think it's way too minor a feature.
> 
>     This would be a lot easier to adopt if there was a working
>     implementation in patch form.
> 
>     Sometimes it would be nice if things like this could be defined
>     using hygienic macros or some other kind of preprocessor or
>     whatever, and imported from a module, rather than requiring major
>     hacking in the parser, the bytecode compiler, and the virtual
>     machine.

I didn't get around to replying when "Parade of the PEPs" was posted.

The Parade of PEPs response surprised me a little.  It seems obvious
to me that dict comprehensions should be in Python if list
comprehensions are, even if no one uses them, on general
considerations of symmetry and the principle of least astonishment
(i.e. I wondered why they weren't both added at the same time).

There are times when it's right to use more abstract grounds than
"importance" to decide to include something.  It's unlikely that
anyone has ever used the numeric literal 901472937 in any Python
program, but if for some reason Python could recognize every numeric
literal except for that one, we'd call it a bug even if the
restriction was described in Python's documentation.  I hope no one
would say Python needn't recognize 901472937 because hardly anyone
wants to specify that particular integer in a program and you can
always say 901472936+1 insead.

The idea of implementing dict comprehensions using macros is
interesting; maybe list comprehensions can be re-done the same way.

Also, if adding dict comprehensions really require "major hacking in
the parser, the bytecode compiler, and the virtual machine", then IMO
a code cleanup is needed that's much larger in scope than adding one
feature.  Certainly no change to the VM should be needed at all, since
the dict comprehension is equivalent to a for loop, and the compiler
can generate the exact same code as the for loop would have.  The
parser and compiler would need a patch, but I'd hope it wouldn't be
"major hacking".

That said, on pragmatic grounds I don't see any terrible urgency to
the issue, and if dict comprehensions don't make it into 2.3 it's no
big deal.  I do hope they get added sooner or later.



More information about the Python-list mailing list