[Python-3000] py3k-struni: proposition to fix ctypes bug, ctypes c_char creates bytes
Thomas Heller
theller at ctypes.org
Wed Aug 8 20:32:48 CEST 2007
Victor Stinner schrieb:
> Hi,
>
> I hear Guido's request to fix last py3k-struni bugs. I downloaded subversion
> trunk and started to work on ctypes tests.
>
> The problem is that ctypes c_char (and c_char_p) creates unicode string
> instead of byte string. I attached a proposition (patch) to change this
> behaviour (use bytes for c_char).
>
> So in next example, it will display 'bytes' and not 'str':
> from ctypes import c_buffer, c_char
> buf = c_buffer("abcdef")
> print (type(buf[0]))
>
> Other behaviour changes:
> - repr(c_char) adds a "b"
> eg. repr(c_char('x')) is "c_char(b'x')" instead of "c_char('x')"
> - bytes is mutable whereas str is not:
> this may break some modules based on ctypes
This patch looks correct. I will test it and then commit if all works well.
The problem I had fixing this is that I was not sure whether the c_char types
should 'contain' bytes objects or str8 objects. str8 will be going away, so
it seems the decision is clear.
OTOH, I'm a little bit confused about the bytes type. I think this behaviour
is a little bit confusing, but maybe that's just me:
>>> b"abc"[:]
b'abc'
>>> b"abc"[:1]
b'a'
>>> b"abc"[1]
98
>>> b"abc"[1] = 42
>>> b"abc"[1] = "f"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer
>>> b"abc"[1] = b"f"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'bytes' object cannot be interpreted as an integer
>>>
Especially confusing is that the repr of a bytes object looks like a string,
but bytes do not contain characters but integers instead.
Thomas
More information about the Python-3000
mailing list