diff options
author | Daniele Varrazzo <daniele.varrazzo@gmail.com> | 2010-12-25 11:57:04 +0100 |
---|---|---|
committer | Daniele Varrazzo <daniele.varrazzo@gmail.com> | 2010-12-31 03:18:27 +0100 |
commit | 2e22eef727fc3b57e63c7a6a1b5cbae9533cd632 (patch) | |
tree | 0454997f99f724358477e3e6900ef9ac497053ea /psycopg/utils.c | |
parent | d3f3f1caf0177f32b70dcb7632ad0a164abcfc65 (diff) | |
download | psycopg2-2e22eef727fc3b57e63c7a6a1b5cbae9533cd632.tar.gz |
Added utility function to convert bytes to string in Python 3.
Diffstat (limited to 'psycopg/utils.c')
-rw-r--r-- | psycopg/utils.c | 24 |
1 files changed, 24 insertions, 0 deletions
diff --git a/psycopg/utils.c b/psycopg/utils.c index e5b221f..16b9249 100644 --- a/psycopg/utils.c +++ b/psycopg/utils.c @@ -118,3 +118,27 @@ psycopg_ensure_bytes(PyObject *obj) return rv; } +/* Take a Python object and return text from it. + * + * On Py3 this means converting bytes to unicode. On Py2 bytes are fine. + * + * The function is ref neutral: steals a ref from obj and adds one to the + * return value. It is safe to call it on NULL. + */ +PyObject * +psycopg_ensure_text(PyObject *obj) +{ +#if PY_MAJOR_VERSION < 3 + return obj; +#else + if (obj) { + /* bytes to unicode in Py3 */ + PyObject *rv = PyUnicode_FromEncodedObject(obj, "utf8", "replace"); + Py_DECREF(obj); + return rv; + } + else { + return NULL; + } +#endif +} |