I need to send an object from a client to a server, but sockets only let you send bytes. How do I convert a custom object to bytes in Python 3.5 so I can send it via the socket?
Asked
Active
Viewed 3,863 times
3 Answers
5
You can serialize the object using pickle
, which will convert it to bytes
and allow you to send it. You can read up on how to use pickle
here

JGrindal
- 793
- 2
- 8
- 23
-
When I try to do that I get TypeError: can't pickle CompiledFFI objects – Jay Howard Nov 09 '17 at 21:50
-
Not all objects can be pickled, like compiled objects (like it sounds like you've got). What type of object are you trying to send? Does the whole object need to be sent, or can you send data about its state only (which isn't precompiled) and send that instead? – JGrindal Nov 09 '17 at 21:53
4
Depends on what you are trying to send over the webs, if it is just some basic dict
or list
of basic types you could serialize it to json
. See here.
If you really want to serialize entire python class then use already mentioned pickle
, although it can be dangerous, see here.
And remember to NOT execute anything deserialized which came from the internet.

scope
- 1,967
- 14
- 15