Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Understand and Parse the Default Python Object Representations

When you print an object in Python, and __repr__ and __str__ are not defined by the user, Python converts the objects to string representations, delimited with angle brackets...

<bound method Shell.clear of <Shell object at 0x112f6f350>>

The problem is rendering this in a web browser in strings that also contain HTML that must be rendered normally. The browser obviously gets confused by the angle brackets.

I'm struggling to find any information about how these representations are formed, if there's a name for them even.

Is it possible to change the way that Python represents objects as strings, for all objects that don't have a __repr__ method defined, by overriding __repr__ for the object class?

So, if Python would normally return "<Foo object at 0x112f6f350>", what hook could make it return "{Foo object at {0x112f6f350}}" instead, or whatever else, without having to modify the Foo and every other class directly?

like image 528
Carl Smith Avatar asked Jan 13 '23 00:01

Carl Smith


1 Answers

You can play with the __builtin__s (before importing anything). I found that replacing __builtin__.repr does not work, but replacing __builtin__.object does.

Here's how it can be done. Say you have a module defining classes:

# foo.py
class Foo(object):
    pass

In your main script, do:

# main.py
import __builtin__

class newobject(object):
    def __repr__(self):
        return '{%s object at {%s}}' % (self.__class__.__name__, hex(id(self)))

__builtin__.object = newobject

from foo import Foo

foo = Foo()
print '%r' % foo

Prints:

{Foo object at {0x100400010}}

NOTE you have given bound method as an example you'd like to handle, but bound methods do have __repr__ defined, and therefor I'm guessing you don't really want a solution which affects them. (check out object().__repr__.__repr__)

like image 74
shx2 Avatar answered Feb 15 '23 19:02

shx2