array and strings in Python 3

Chris Rebert clp2 at rebertia.com
Sat Dec 11 20:48:27 EST 2010


On Sat, Dec 11, 2010 at 5:32 PM, wander.lairson
<wander.lairson at gmail.com> wrote:
> Hello,
>
> This is my first post on python mailing list. I've working in code
> which must run on python 2 and python 3. I am using array.array as
> data buffers. I am stuck with the following code line, which works on
> Python 2, but not on Python 3.1.2:
>
>>>> import array
>>>> array.array('B', 'test')
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> TypeError: an integer is required
>
> According to Python 3 documentation (as far as I understood it), it
> should work.

I think you forgot to keep in mind the changes in bytes vs. unicode in
Python 3 when reading the docs.

> Again, no problem on Python 2. I've googled for people
> with similar problems, but got nothing. Does anyone have an idea what
> could I be doing wrong?

Recall that string handling changed incompatibly between Python 2 and
Python 3. Your 'test' was a bytestring in Python 2 but is now a
*Unicode string* in Python 3.

The `array` module's handling of strings changed as well. Reading the
Python 3 docs @ http://docs.python.org/dev/library/array.html , we
find (all emphases added):
class array.array(typecode[, initializer])
    [...]
    If given a list or string, the initializer is passed to the new
array’s fromlist(), frombytes(), or **fromunicode()** method (see
below) to add initial items to the array. Otherwise, the iterable
initializer is passed to the extend() method.
[...]
array.fromunicode(s)
    Extends this array with data from the given unicode string. The
array **must be a type 'u' array**; **otherwise a ValueError is
raised**. Use array.frombytes(unicodestring.encode(enc)) to append
Unicode data to an array of some other type.

Since your array's typecode is not 'u', you're getting a ValueError
just like the docs say.

Try using a bytestring instead:
array.array('B', b"test") # Note the b prefix

Incidentally, if you ran 2to3 over your code and weren't warned about
this change in the array module, then that's probably a bug in 2to3
which ought to be reported: http://bugs.python.org

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list