Julien Guigner
Julien Guigner

Reputation: 193

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 ?

Upvotes: 8

Views: 7133

Answers (1)

Ned Batchelder
Ned Batchelder

Reputation: 376052

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.

Upvotes: 5

Related Questions