Reconstruct Python objects from a text view

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

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

Or as soon as an object is presented in stdout, does it receive GCd?

It doesn't really matter, but it can be useful when playing with the Python CLI.

+3
source share
3 answers

Output reprcan restore an object, but there is agreement if it has bits surrounded by angle brackets, then these bits are not restored.

So, in this case, you cannot restore the socket, and yes, it will be garbage collected immediately.

+2
source

, repr , repr, . .

. :

class ReprObject(object):
    def __init__(self, value, item):
        self.value = value
        self.item = item

    def __repr__(self):
        return '%s(**%r)' % (self.__class__.__name__, self.__dict__)

, :

>>> r = ReprObject(value=1, item=True)
>>> r
ReprObject(**{'item': True, 'value': 1})

/ repr :

>>> r2 = ReprObject(**{'item': True, 'value': 1})
>>> r2
ReprObject(**{'item': True, 'value': 1})

eval() :

>>> eval(repr(r2))
ReprObject(**{'item': True, 'value': 1})
+1

All Articles