How to understand and analyze default views of Python objects

When you print an object in Python, as well __repr__, and __str__are not determined by the user, Python converts the object to a string, limited angular 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 should render normally. The browser is clearly confused by angle brackets.

I am trying to find any information on how these views are formed, if there is a name for them.

Is it possible to change the way that Python represents objects as strings, for all objects that do not have a method __repr__, by overriding the __repr__class object?

So, if Python usually returned "<Foo object at 0x112f6f350>", which hook could make it return "{Foo object at {0x112f6f350}}"instead, or something else, without the need to directly modify Fooevery other class?

+4
source share
2 answers

They are not my objects. This is for the shell, so the user will be able to print any material that they like. If they print a list of 3 Foos, in a browser-based client, they should not receive a list of three broken [invisible] HTML elements. I am trying to configure Python so that all objects that were presented after the settings are displayed differently by default.

In this case, you can change sys.displayhook():

import sys
from cgi import escape
try:
    import __builtin__ as builtins
except ImportError: # Python 3
    import builtins

def html_displayhook(value):
    if value is None:
        return
    text = escape(repr(value)) # <-- make html-safe text
    sys.stdout.write(text)
    sys.stdout.write("\n")
    builtins._ = value   

sys.displayhook = html_displayhook

, html , html, .

+2

__builtin__ ( -). , __builtin__.repr , __builtin__.object .

. , , :

# foo.py
class Foo(object):
    pass

script :

# 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

{Foo object at {0x100400010}}

, bound method , , __repr__, , , . ( object().__repr__.__repr__)

+7

All Articles