From 78ed6f866d6322f3a73e2cb0503fecbb18834782 Mon Sep 17 00:00:00 2001 From: Thomas Grainger Date: Thu, 19 Mar 2020 11:23:49 +0000 Subject: [PATCH] add python_2_bytes_compatible --- six.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/six.py b/six.py index 5fe9f8e14..2dbc36a6c 100644 --- a/six.py +++ b/six.py @@ -955,6 +955,23 @@ def python_2_unicode_compatible(klass): return klass +def python_2_bytes_compatible(klass): + """ + A class decorator that defines __str__ and __bytes__ methods under Python 2. + Under Python 3 it does nothing. + + To support Python 2 and 3 with a single code base, define a __bytes__ method + returning bytes and apply this decorator to the class. + """ + if PY2: + if '__bytes__' not in klass.__dict__: + raise ValueError("@python_2_bytes_compatible cannot be applied " + "to %s because it doesn't define __bytes__()." % + klass.__name__) + klass.__str__ = klass.__bytes__ + return klass + + # Complete the moves implementation. # This code is at the end of this module to speed up module loading. # Turn this module into a package.