[Tutor] UDP client

Peter Otten __peter__ at web.de
Sun Feb 26 03:33:43 EST 2017


Phil wrote:

> Thank you for reading this.
> 
> As an exercise, and for no other purpose, I'm trying to convert some C++
> code that I put together 17 years ago. I'm very rusty and hours of
> Internet searches have made me more confused that I was to start with.
> 
> The following works under Python2 but not under Python3.

> data = "GET_LIST"

This is a sequence of bytes in Python 2 and a sequence of unicode codepoints 
in Python 3. You are using a low-level protocol and need bytes

data = b"GET_LIST"

If your original data is a string you have to encode, for example

data = "Möglich".encode("utf-8")

> So, is this reasonable UDP client code and what have I overlooked to get
> this to work under Python3?

You ran into one of the most prominent changes between Python 2 and 3. In 
py3 you have to be explicit if you want bytes

b"bytes", "unicode", u"unicode"

which resembles the needs of most users while in py2 you have to be explicit 
if you want unicode

b"bytes", "bytes", u"unicode"

which in combination with implicit conversion led to many bugs that only 
users in non-ascii-land would encounter.




More information about the Tutor mailing list