Patchwork [18,of,18,helps-py3] check-code: disallow use of dict(key=value) construction

login
register
mail settings
Submitter Augie Fackler
Date March 12, 2014, 5:40 p.m.
Message ID <a61ed1c2d7a70c6cc8c4.1394646052@augie-macbookair>
Download mbox | patch
Permalink /patch/3925/
State Accepted
Commit a61ed1c2d7a70c6cc8c4a592f6d32dafc901361f
Headers show

Comments

Augie Fackler - March 12, 2014, 5:40 p.m.
# HG changeset patch
# User Augie Fackler <raf@durin42.com>
# Date 1394645487 14400
#      Wed Mar 12 13:31:27 2014 -0400
# Node ID a61ed1c2d7a70c6cc8c4a592f6d32dafc901361f
# Parent  7d4d04299927ab9cba7bef9e3b474120a1a84292
check-code: disallow use of dict(key=value) construction

{} literals are faster and more consistent across Python 2 and 3.

Whitelisted the one use of dict() that is using a generator expresion.

Patch

diff --git a/contrib/check-code.py b/contrib/check-code.py
--- a/contrib/check-code.py
+++ b/contrib/check-code.py
@@ -200,6 +200,8 @@ 
      'use "import foo.bar" on its own line instead.'),
     (r'(?<!def)\s+(cmp)\(', "cmp is not available in Python 3+"),
     (r'\breduce\s*\(.*', "reduce is not available in Python 3+"),
+    (r'dict\(.*=', 'dict() is different in Py2 and 3 and is slower than {}',
+     'dict-from-generator'),
     (r'\.has_key\b', "dict.has_key is not available in Python 3+"),
     (r'\s<>\s', '<> operator is not available in Python 3+, use !='),
     (r'^\s*\t', "don't use tabs"),
diff --git a/hgext/largefiles/remotestore.py b/hgext/largefiles/remotestore.py
--- a/hgext/largefiles/remotestore.py
+++ b/hgext/largefiles/remotestore.py
@@ -30,7 +30,8 @@ 
             % (source, util.hidepassword(self.url)))
 
     def exists(self, hashes):
-        return dict((h, s == 0) for (h, s) in self._stat(hashes).iteritems())
+        return dict((h, s == 0) for (h, s) in # dict-from-generator
+                    self._stat(hashes).iteritems())
 
     def sendfile(self, filename, hash):
         self.ui.debug('remotestore: sendfile(%s, %s)\n' % (filename, hash))
@@ -97,4 +98,3 @@ 
     def batch(self):
         '''Support for remote batching.'''
         return remotebatch(self)
-
diff --git a/tests/test-check-code.t b/tests/test-check-code.t
--- a/tests/test-check-code.t
+++ b/tests/test-check-code.t
@@ -123,6 +123,7 @@ 
   $ cat > python3-compat.py << EOF
   > foo <> bar
   > reduce(lambda a, b: a + b, [1, 2, 3, 4])
+  > dict(key=value)
   > EOF
   $ "$check_code" python3-compat.py
   python3-compat.py:1:
@@ -131,6 +132,9 @@ 
   python3-compat.py:2:
    > reduce(lambda a, b: a + b, [1, 2, 3, 4])
    reduce is not available in Python 3+
+  python3-compat.py:3:
+   > dict(key=value)
+   dict() is different in Py2 and 3 and is slower than {}
   [1]
 
   $ cat > is-op.py <<EOF