2

I'm writing code that's supposed to be Python 2.7 and Python 3.3+ compatible. When trying to run my code with Python 2.7, I get the following problem.

I'm importing unicode_literals from __future__ in each file and I'm having trouble getting the array function to work.

from array import array
from __future__ import unicode_literals

Trying to make a character array doesn't work

array("c", "test")
> TypeError: must be char, not unicode

Trying to make a unicode array also doesn't work

array("u", "test")
> TypeError: must be char, not unicode

Can I make an array that is compatible with unicode_literals?

2
  • Any reason you can't use list? Commented May 22, 2016 at 21:03
  • @Ownaginatious I'm working on legacy code so I would rather not have to rewrite the function to use list, that might be the best option, though Commented May 22, 2016 at 21:06

2 Answers 2

6

This error is being thrown because of the first argument to array(), the typecode. In Python 2 this must be a non-unicode character (string of length 1), and in Python 3 this must be a unicode character. Since both of these are the meaning of str in the respective Python versions, this works in both:

array(str('u'), 'test')
Sign up to request clarification or add additional context in comments.

Comments

3

This is a limitation of the array module that was fixed recently (https://bugs.python.org/issue20014). On Python 2.7.11 (or newer) the array constructor will accept both str and unicode as the first argument.

As a workaround you can use e.g. array(str("u"), "test"). I'm referring to the other answer by Dan Getz for an explanation of why this works.

Note that your first example using the "c" typecode still won't work on either Python 2.7 or Python 3.x. On Python 2.7, you need to pass a bytestring as the second argument (e.g. by passing b"test" as the second argument). The "c" typecode was removed in Python 3.0, so you should use "b" or "B" instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.