Arc
Arc

Reputation: 11296

How do I use pywintypes.Unicode()?

How do I use pywintypes.Unicode in Python 3.3.5?

import pywintypes
pywintypes.Unicode("s")

This produces an error:

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    pywintypes.Unicode("s")
TypeError: must be impossible<bad format char>, not str

I've seen other code uses that look the same to me, so what is wrong here?

Upvotes: 2

Views: 892

Answers (1)

Arc
Arc

Reputation: 11296

TL;DR: It's a bug affecting Python 3, and you don't need pywintypes.Unicode(text) in Python 3. Just use text directly if you need a string and bytes(text, encoding) if you need them as bytes.

The error

TypeError: must be impossible<bad format char>, not str

hints at the bad format char in the C++ source, t#, which is impossible (unknown).

Thanks to eryksun's comments and by looking at the documentation pages of PyArg_ParseTuple() for Python 2 and Python 3, it becomes clear that the bug is in win32/src/PyWinTypesmodule.cpp.

PYWINTYPES_EXPORT PyObject *PyWin_NewUnicode(PyObject *self, PyObject *args)
{
    char *string;
    int slen;
    if (!PyArg_ParseTuple(args, "t#", &string, &slen)) // <-- BUG: Python 2 format char
        return NULL;
    return PyUnicode_DecodeMBCS(string, slen, NULL);
}

t# only exists for Python 2, for Python 3 it should be something like s*, and according to eryksun, MBCS-decoding is unnecessary as Python already handles Unicode strings automatically.

Upvotes: 2

Related Questions