This will result in a `UnicodeDecodeError` in *all cases* except when `data` contains only ascii-characters, in which case `encode()` is unnecessary anyway. The reason is that when you are calling `encode()` on a `str`, the `str` is first decoded to `unicode`, assuming `ascii` encoding, and then encoded back into a `str` using the specified encoding (`utf-8` in this case). What you want to do is make sure that `msg` is `unicode`.