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 ?
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.
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.
But what about a string? A string is composed of: An 8-byte object header (4-byte SyncBlock and a 4-byte type descriptor)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With