Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reconstructing Python objects from text representation

Tags:

python

object

Is it possible to create an object from the represented text of python objects when they are represented on the screen?

>>> select.select([s], [],[])
([<socket._socketobject object at 0x7f274914c600>], [], [])
>>> eval('<socket._socketobject object at 0x7f274914c600>') # Fail

Or once the object is represented to stdout, does it get GCd?

Not of significant use, but when playing with the Python CLI, it might be occasionally helpful.

like image 485
tMC Avatar asked Jan 31 '26 20:01

tMC


2 Answers

The output of repr may be able to reconstruct the object, however the convention is, if it has bits surrounded by angle brackets then those bits aren't reconstructible.

So in this case you can't reconstruct the socket, and yes it will be garbage collected straight away.

like image 100
Nick Craig-Wood Avatar answered Feb 02 '26 11:02

Nick Craig-Wood


It is not, as apparently text presentation does not necessarily contain all information of the object.

If you want to text-like object representation try JSON module.

http://docs.python.org/library/json.html?highlight=json#json

Also please note that objects encapsulated in this presentation cannot have native object bindings, like sockets, file handles, etc.

like image 27
Mikko Ohtamaa Avatar answered Feb 02 '26 10:02

Mikko Ohtamaa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!