python backports for some methods
Asked Answered
F

2

2

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

any, all, collections.defaultdict, collections.deque
Fusillade answered 24/9, 2010 at 8:36 Comment(2)
What saddens me is that I had to look for, found (and appreciate!) this question and the accepted answer today, in 2013. :-]Lauder
The same for me, in 2016 … :-(Fulmar
V
5

Well, at least for any and all it's easy:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

deque is already in 2.4.

As for defaultdict, I guess you can emulate that easily with setdefault().

Quoting from Alex Martelli`s (and others') highly recommended Python Cookbook:

This is what the setdefault method of dictionaries is for. Say we’re building a word-to-page-numbers index, a dictionary that maps each word to the list of page numbers where it appears. A key piece of code in that application might be:

def addword(theIndex, word, pagenumber):
    theIndex.setdefault(word, [ ]).append(pagenumber)

This code is equivalent to more verbose approaches such as:

def addword(theIndex, word, pagenumber):
    if word in theIndex:
        theIndex[word].append(pagenumber)
    else:
        theIndex[word] = [pagenumber]

and:

def addword(theIndex, word, pagenumber):
    try:
        theIndex[word].append(pagenumber)
    except KeyError:
        theIndex[word] = [pagenumber]
Vetchling answered 24/9, 2010 at 8:40 Comment(0)
C
5

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.

Cynthia answered 24/9, 2010 at 8:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.