[PATCH 4 of 5 V2] py3: provide (del|get|has|set)attr wrappers that accepts bytes

Yuya Nishihara yuya at tcha.org
Tue Aug 16 04:50:45 EDT 2016


# HG changeset patch
# User Yuya Nishihara <yuya at tcha.org>
# Date 1471146681 -32400
#      Sun Aug 14 12:51:21 2016 +0900
# Node ID 82f7a2639ea514b22a2cbb2000740dce513663e2
# Parent  c3639410ef41ee95ce795ac1a461889feb9f9cf5
py3: provide (del|get|has|set)attr wrappers that accepts bytes

These functions will be imported automagically by our code transformer.

getattr() and setattr() are widely used in our code. We wouldn't probably
want to rewrite every single call of getattr/setattr. delattr() and hasattr()
aren't that important, but they are functions of the same kind.

diff --git a/mercurial/pycompat.py b/mercurial/pycompat.py
--- a/mercurial/pycompat.py
+++ b/mercurial/pycompat.py
@@ -31,8 +31,22 @@ else:
 
 if sys.version_info[0] >= 3:
     import builtins
+    import functools
     builtins.xrange = range
 
+    def _wrapattrfunc(f):
+        @functools.wraps(f)
+        def w(object, name, *args):
+            if isinstance(name, bytes):
+                name = name.decode(u'utf-8')
+            return f(object, name, *args)
+        return w
+
+    delattr = _wrapattrfunc(builtins.delattr)
+    getattr = _wrapattrfunc(builtins.getattr)
+    hasattr = _wrapattrfunc(builtins.hasattr)
+    setattr = _wrapattrfunc(builtins.setattr)
+
 stringio = io.StringIO
 empty = _queue.Empty
 queue = _queue.Queue


More information about the Mercurial-devel mailing list