@@ -99,3 +99,64 @@ def RunWithCrashHandler(f):
9999 # Ignore stdin being closed. This happens during some tests.
100100 pass
101101 sys .exit (127 )
102+
103+
104+ # Pick one of two defaultdict implementations. A native version was added to
105+ # the collections library in python 2.5. If that is not available use Jason's
106+ # pure python recipe. He gave us permission to distribute it.
107+
108+ # On Mon, Nov 30, 2009 at 07:27, jason kirtland <jek at discorporate.us> wrote:
109+ # >
110+ # > Hi Tom, sure thing! It's not easy to find on the cookbook site, but the
111+ # > recipe is under the Python license.
112+ # >
113+ # > Cheers,
114+ # > Jason
115+ # >
116+ # > On Thu, Nov 26, 2009 at 3:03 PM, Tom Brown <tom.brown.code@gmail.com> wrote:
117+ # >
118+ # >> I would like to include http://code.activestate.com/recipes/523034/ in
119+ # >> http://code.google.com/p/googletransitdatafeed/wiki/TransitFeedDistribution
120+ # >> which is distributed under the Apache License, Version 2.0 with Copyright
121+ # >> Google. May we include your code with a comment in the source pointing at
122+ # >> the original URL? Thanks, Tom Brown
123+
124+ try :
125+ # Try the native implementation first
126+ from collections import defaultdict
127+ except :
128+ # Fallback for python2.4, which didn't include collections.defaultdict
129+ class defaultdict (dict ):
130+ def __init__ (self , default_factory = None , * a , ** kw ):
131+ if (default_factory is not None and
132+ not hasattr (default_factory , '__call__' )):
133+ raise TypeError ('first argument must be callable' )
134+ dict .__init__ (self , * a , ** kw )
135+ self .default_factory = default_factory
136+ def __getitem__ (self , key ):
137+ try :
138+ return dict .__getitem__ (self , key )
139+ except KeyError :
140+ return self .__missing__ (key )
141+ def __missing__ (self , key ):
142+ if self .default_factory is None :
143+ raise KeyError (key )
144+ self [key ] = value = self .default_factory ()
145+ return value
146+ def __reduce__ (self ):
147+ if self .default_factory is None :
148+ args = tuple ()
149+ else :
150+ args = self .default_factory ,
151+ return type (self ), args , None , None , self .items ()
152+ def copy (self ):
153+ return self .__copy__ ()
154+ def __copy__ (self ):
155+ return type (self )(self .default_factory , self )
156+ def __deepcopy__ (self , memo ):
157+ import copy
158+ return type (self )(self .default_factory ,
159+ copy .deepcopy (self .items ()))
160+ def __repr__ (self ):
161+ return 'defaultdict(%s, %s)' % (self .default_factory ,
162+ dict .__repr__ (self ))
0 commit comments