[Python-ideas] Compact repr operator (i.e., __short_repr__)

Steven D'Aprano steve at pearwood.info
Thu Feb 11 05:59:41 EST 2016


On Thu, Feb 11, 2016 at 01:24:42AM -0800, Mahmoud Hashemi wrote:

> I still think you're selling repr short. It can be much more. One day we
> might have:
> 
> >>> repr(obj, pretty=True, depth=2, width=120)

I'm sympathetic, but I'm not sure that repr() is the right place to be 
focusing. repr() is too closely tied to the REPL and the existing 
string formatting codes to start making radical changes. But we do have 
the pprint library, which (in my opinion) is underpowered and underused.

I know that some people think that Python already has too many string 
conversion functions ( str()/__str__ and repr()/__repr__ ) but for my 
own use I've occasionally found that it has too few.

Some time ago, I started working on a library for continued fractions. I 
count at least five useful/standard representations for a continued 
fraction. All of these would be equivalent:

ContinuedFraction(1, 2, 3, 4, 5)

[1; 2, 3, 4, 5]

1 + 1/(2 + 1/(3 + 1/(4 + 1/5)))


      1     1     1     1
1 + ----- ----- ----- -----
    2 +   3 +   4 +     5



            1
1 + -----------------
              1
    2 + -------------
                1
        3 + ---------
                  1
            4 + -----
                  5


(Apart from the first, the remaining four are standard notations used 
in mathematics.)

Now obviously I can just add my own string conversion methods to the 
class, but it would be nice to be able to integrate with the pprint (and 
maybe reprlib) libraries in some way rather than an ad hoc set of 
arbitrarily named methods?

I must admit that I'm just thinking aloud here, I don't actually have a 
concrete idea. But maybe my use-case will spark an idea in someone else.



-- 
Steve


More information about the Python-ideas mailing list