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

login
register
mail settings
Submitter Yuya Nishihara
Date Aug. 16, 2016, 8:50 a.m.
Message ID <82f7a2639ea514b22a2c.1471337445@mimosa>
Download mbox | patch
Permalink /patch/16321/
State Accepted
Headers show

Comments

Yuya Nishihara - Aug. 16, 2016, 8:50 a.m.
# HG changeset patch
# User Yuya Nishihara <yuya@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.

Patch

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