python: Add compatability helpers to determine if type is really bytes
authorNoel Power <noel.power@suse.com>
Wed, 7 Mar 2018 14:39:54 +0000 (14:39 +0000)
committerAndrew Bartlett <abartlet@samba.org>
Fri, 23 Mar 2018 06:28:25 +0000 (07:28 +0100)
py3compat has PyBytes_Check macro which evalates to PyString_Check in
python2. To help switch behaviour based on whether you are dealing
with the bytes type the following macros have been added.

IsPy3Bytes
IsPy3BytesOrString

IsPy3Bytes will evaluate to false in python2 and will return the
expected result in python3. IsPy3BytesOrString will test for string
type alone in python2 or bytes and string in python3.

Signed-off-by: Noel Power <noel.power@suse.com>
Reviewed-by: Douglas Bagnall <douglas.bagnall@catalyst.net.nz>
Reviewed-by: Andrew Bartlett <abartlet@samba.org>
python/py3compat.h

index ce317c65f8e2ddca8c8ddd6f2829e0b523e516c1..5fa57f323d528a113ae6140df7abc42e1a2c3013 100644 (file)
 #define PY_DESC_PY3_BYTES "bytes"
 #define PY_DESC_PY3_STRING "string"
 
+/* Determine if object is really bytes, for code that runs
+ * in python2 & python3 (note: PyBytes_Check is replaced by
+ * PyString_Check in python2) so care needs to be taken when
+ * writing code that will check if incoming type is bytes that
+ * will work as expected in python2 & python3
+ */
+
+#define IsPy3Bytes PyBytes_Check
+
+#define IsPy3BytesOrString(pystr) \
+    (PyStr_Check(pystr) || PyBytes_Check(pystr))
+
+
 /* Ints */
 
 #define PyInt_Type PyLong_Type
 #define PY_DESC_PY3_BYTES "string"
 #define PY_DESC_PY3_STRING "unicode"
 
+/* Determine if object is really bytes, for code that runs
+ * in python2 & python3 (note: PyBytes_Check is replaced by
+ * PyString_Check in python2) so care needs to be taken when
+ * writing code that will check if incoming type is bytes that
+ * will work as expected in python2 & python3
+ */
+
+#define IsPy3Bytes(pystr) false
+
+#define IsPy3BytesOrString PyStr_Check
+
 /* PyArg_ParseTuple/Py_BuildValue argument */
 
 #define PYARG_BYTES_LEN "s#"