Optimization of __len__() in cgi.py

Bob Kline bkline at rksystems.com
Wed Aug 16 11:56:26 EDT 2006


Marc 'BlackJack' Rintsch wrote:
>>     def keys(self):
>>         return {}.fromkeys([i.name for i in self.list]).keys()
> 
> This does not maintain the order of `self.list`.  Don't know if there's
> code relying on this.

Such code would be flying in the face of an implication that the order
of the keys is *not* preserved, as the keys() method is documented as
"Dictionary style keys() method" (and the documentation for dictionary
keys() says "... listed in an arbitrary order which is non-random ...").

If it were decided that the behavior of keys() should be preserved even
to the extent of preserving the order of the first occurrence of each
field name, then the optimization could just be moved to __len__():

    def __len__(self):
        return len({}.fromkeys([i.name for i in self.list]))

> But maybe it's even faster to change `FieldStorage.__len__()` to return
> the length of `self.list` directly without the need to create an
> intermediate list that's thrown away immediately.

This approach also risks breaking code that assumes it's getting the
number of unique field names (an assumption which in this case would be
justified, given the documentation of the keys() method quoted above).

Bob



More information about the Python-list mailing list