Package nltk :: Module compat
[hide private]
[frames] | no frames]

Source Code for Module nltk.compat

 1  # Natural Language Toolkit: Compatibility Functions 
 2  # 
 3  # Copyright (C) 2001-2008 NLTK Project 
 4  # Author: Steven Bird <[email protected]> 
 5  #         Edward Loper <[email protected]> 
 6  # URL: <http://nltk.org> 
 7  # For license information, see LICENSE.TXT 
 8   
 9  """ 
10  Backwards compatibility with previous versions of Python. 
11   
12  This module provides backwards compatibility by defining 
13  functions and classes that were not available in earlier versions of 
14  Python.  Intented usage: 
15   
16      >>> from nltk.compat import * 
17   
18  Currently, NLTK requires Python 2.4 or later. 
19  """ 
20   
21  ###################################################################### 
22  # New in Python 2.5 
23  ###################################################################### 
24   
25  # ElementTree 
26   
27  try: 
28      from xml.etree import ElementTree 
29  except ImportError: 
30      from nltk.etree import ElementTree 
31   
32  # collections.defaultdict 
33  # originally contributed by Yoav Goldberg <[email protected]> 
34  # new version by Jason Kirtland from Python cookbook. 
35  # <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/523034> 
36  try: 
37      from collections import defaultdict 
38  except ImportError: 
39 - class defaultdict(dict):
40 - def __init__(self, default_factory=None, *a, **kw):
41 if (default_factory is not None and 42 not hasattr(default_factory, '__call__')): 43 raise TypeError('first argument must be callable') 44 dict.__init__(self, *a, **kw) 45 self.default_factory = default_factory
46 - def __getitem__(self, key):
47 try: 48 return dict.__getitem__(self, key) 49 except KeyError: 50 return self.__missing__(key)
51 - def __missing__(self, key):
52 if self.default_factory is None: 53 raise KeyError(key) 54 self[key] = value = self.default_factory() 55 return value
56 - def __reduce__(self):
57 if self.default_factory is None: 58 args = tuple() 59 else: 60 args = self.default_factory, 61 return type(self), args, None, None, self.iteritems()
62 - def copy(self):
63 return self.__copy__()
64 - def __copy__(self):
65 return type(self)(self.default_factory, self)
66 - def __deepcopy__(self, memo):
67 import copy 68 return type(self)(self.default_factory, 69 copy.deepcopy(self.items()))
70 - def __repr__(self):
71 return 'defaultdict(%s, %s)' % (self.default_factory, 72 dict.__repr__(self))
73 74 # [XX] to make pickle happy in python 2.4: 75 import collections 76 collections.defaultdict = defaultdict 77 78 __all__ = ['ElementTree', 'defaultdict'] 79