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?
They're not my objects chap. It's for a shell, so the user will be able to print any stuff they like. If they print a list of 3 Foos, in a browser based client, they should not get a list of three broken [invisible] HTML elements. I'm after a way to tweak Python so that all objects that are represented after the tweaks are made, are rendered differently to the default.
In that case, you could 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
It prints html-safe object representations by default and it doesn't prevent users from printing a raw html if they like it.