Where is the function of Repr.repr1() in this example?

fl rxjwg98 at gmail.com
Wed Jul 23 17:37:32 EDT 2014


Hi,
I run the example code below from website: 

https://docs.python.org/2/library/repr.html#repr.Repr.repr1

If I run these lines from an editor, it echoes:

>>> <open file '<...at 0x01EF4020>
>>> dsfdsf         # entered letters


If I only run the last line (hoping the same effect with running from the editor)
it simply echoes:

>>> print aRepr.repr(sys.stdin)
<open file '<...at 0x01EF4020>
>>> 


I have these questions about this example code:

1. What purpose of the author wants from the example code? 
2. I do not see Repr.repr1() in the code snippet. Why did the author mention
that first?
3. Why is it different from running the last line directly in the Interactive 
Window, and within an editor file?


Thanks,



..................
The use of dynamic dispatching by Repr.repr1() allows subclasses of Repr to add 
support for additional built-in object types or to modify the handling of types
already supported. This example shows how special support for file objects could
be added:

import repr as reprlib
import sys

class MyRepr(reprlib.Repr):
    def repr_file(self, obj, level):
        if obj.name in ['<stdin>', '<stdout>', '<stderr>']:
            return obj.name
        else:
            return repr(obj)

aRepr = MyRepr()
print aRepr.repr(sys.stdin)          # prints '<stdin>'



More information about the Python-list mailing list