[PATCH 1 of 2 RFC] util: adding support for defaultdict

Nicolas Dumazet nicdumz at gmail.com
Sat Aug 22 16:53:40 CDT 2009


# HG changeset patch
# User Nicolas Dumazet <nicdumz.commits at gmail.com>
# Date 1250845059 -7200
# Node ID d592614e7f2e9fe3ce844e4c5d3d591a61c1832e
# Parent  642febca0e5df1a7cf628f30de94841b24e33ce5
util: adding support for defaultdict

defaultdict is available from Python 2.5

diff --git a/mercurial/util.py b/mercurial/util.py
--- a/mercurial/util.py
+++ b/mercurial/util.py
@@ -36,6 +36,30 @@
     _fastsha1 = sha1 = _sha1
     return _sha1(s)
 
+def defaultdict(factory):
+    return _fastdefaultdict(factory)
+
+def _fastdefaultdict(factory):
+    # Import defaultdict from collections if available
+    # or implement it in Python, and overwrite itself
+    # with it on the first call.
+    try:
+        # Python >= 2.5
+        from collections import defaultdict as _defaultdict
+    except ImportError:
+        # Python 2.4
+        class _defaultdict(dict):
+            def __init__(self, factory):
+                dict.__init__(self)
+                self.factory = factory
+
+            def __getitem__(self, key):
+                return self.setdefault(key, self.factory())
+
+    global _fastdefaultdict
+    _fastdefaultdict = _defaultdict
+    return _defaultdict(factory)
+
 import subprocess
 closefds = os.name == 'posix'
 def popen2(cmd):


More information about the Mercurial-devel mailing list