[Python-3000] A few small py3k wishes

Alex Martelli aleaxit at gmail.com
Mon Apr 3 00:08:10 CEST 2006


On Apr 2, 2006, at 2:39 PM, Talin wrote:
    ...
> -- An easy way to iterate over key, value pairs in a dict in
> sorted order. Currently you have to get the list of keys,
> sort them, and then lookup each value, OR you have to
> get the list of tuples and call sorted() with a key= arg
> containing a lambda function that extracts the first
> tuple element.

I believe this assertion is severely mistaken.  Please give one  
example of a dictionary d where your proposed, contorted idea:

for k, v in sorted(d.items(), key=lambda kv: kv[0]): ...

makes ANY difference compared to the streamlined and effective "one  
and only obvious way to do it":

for k, v in sorted(d.iteritems()):

considering that:

a. keys are unique (no two distinct keys can ever compare equal),  
therefore that key=... clause is totally unneeded;

b. from sorted's viewpoint, it makes no difference whether its  
argument is a list or any other iterable, therefore it's a pure waste  
of memory (in Python 2.*) to pass it d.items() ["the list of tuples",  
as you call it] where d.iteritems() will do just fine.

Personally, despite having just claimed that the above is "the one  
and only obvious way", I find the following quite fine too:

for k in sorted(d):
     v = d[k]
     ...

Yes, that's your dreaded "lookup each value", but it's nowhere as  
dreadful as you make it sound -- just about equivalent, in both  
lexical conciseness and conceptual clarity, to "the one and only  
obvious way".

> -- A mechanism whereby imported modules can import
> symbols from the module that imported them. (Specifically,
> I want to take a bunch of variables in my __main__ module
> and make them accessible to the imported module.)

A module can be imported several times, from many other modules,  
although the "import machinery" only LOADS each module once (save for  
explicit reload(...) calls).  Are you proposing that the symbols  
being imported by module X should depend on the half-accident of what  
other module happens to import X _FIRST_?!

If you want to have X import from __main__, doing so by "from  
__main__ import ..." is simple, clear, and obvious -- and needs  
absolutely no change whatsoever in Python, since it works just fine  
today, of course.


I don't like any of these proposals, but these two are particularly  
egregious, particularly the first one I've quoted, as it rests on an  
obviously erroneous assertion.


Alex




More information about the Python-3000 mailing list