Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2 to 3 bytes/string error

I'm trying to convert a Python library made for Python 2 to Python 3, here is the code.

I have an error at line 152. In the Py2 version, the function is:


def write(self, data):
    self._write_buffer += data

The error is:

TypeError: Can't convert 'bytes' object to str implicitly

I found that I've to decode the variable, so I changed the function to:


def write(self, data):
    self._write_buffer += data.decode('utf8')

It works but I have another error in the asyncore library which said that

(the Type) must be bytes or buffer, not str

So, what can I do ?

like image 920
Julien Guigner Avatar asked Nov 05 '10 08:11

Julien Guigner


People also ask

How many bytes does string take in Python?

Note that every string in Python takes additional 49-80 bytes of memory, where it stores supplementary information, such as hash, length, length in bytes, encoding type and string flags. That's why an empty string takes 49 bytes of memory.

What are byte strings in Python?

In Python, a byte string is just that: a sequence of bytes. It isn't human-readable. Under the hood, everything must be converted to a byte string before it can be stored in a computer. On the other hand, a character string, often just called a "string", is a sequence of characters. It is human-readable.

How many bytes is a string?

But what about a string? A string is composed of: An 8-byte object header (4-byte SyncBlock and a 4-byte type descriptor)


1 Answers

You need to be clear about where you want bytes and where you want strings. If you simply add decode and encode where the errors appear, you will be playing whack-a-mole. In your case, you are writing a socket implementation. Sockets deal with bytes, not strings. So I would think your _write_buffer should be a bytes object, not a string as you now have it.

Line 91 should change to:

self._write_buffer = b''

Then you can work from there to ensure that you use bytes throughout.

like image 119
Ned Batchelder Avatar answered Oct 18 '22 03:10

Ned Batchelder