python backports for some methods

后端 未结 2 1912
南笙
南笙 2021-01-14 21:08

Is there any backport for the following methods to work with python 2.4:

any, all, collections.defaultdict, collections.deque
2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-14 21:26

    As Tim points out, all and any are trivial. defaultdict isn't much more difficult. Here's a passable implementation I believe. It's essentially a translation of the docs into code.

    update: removed ternary expression because I remembered that that's not in 2.4

    class defaultdict(dict):
         def __init__(self, default_factory, *args, **kwargs):
             super(defaultdict, self).__init__(*args, **kwargs)
             self.default_factory = default_factory
    
         def __missing__(self, key):
             try:
                 self[key] = self.default_factory()
             except TypeError:
                 raise KeyError("Missing key %s" % (key, ))
             else:
                 return self[key]
    
         def __getitem__(self, key):
             try:
                 return super(defaultdict, self).__getitem__(key)
             except KeyError:
                 return self.__missing__(key)
    

    If you are just using it to build a dict, then you might want to change the EAFP to LBYL for __getitem__. right now it's optimized to build the dict and then use it for a while with a lot of non-miss lookups.

    deque is going to be tougher. I wish I had the time to do that just because It's probably my favorite out of collections but it's non trivial. never mind. Just read Tims post all the way through. You got your wish.

提交回复
热议问题