سؤال

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?

هل كانت مفيدة؟

المحلول 2

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.

نصائح أخرى

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__)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top