[Python-ideas] Reprs of classes and functions (original) (raw)

Steven D'Aprano steve at pearwood.info
Wed Feb 25 11:25:21 CET 2015


On Wed, Feb 25, 2015 at 10:12:03AM +0200, Serhiy Storchaka wrote:

This idea is already casually mentioned, but sank deep into the threads of the discussion. Raise it up.

Currently reprs of classes and functions look as: >>> int <class 'int'> >>> int.frombytes <built-in method frombytes of type object at 0x826cf60> >>> open >>> import collections >>> collections.Counter <class 'collections.Counter'> >>> collections.Counter.fromkeys <bound method Counter.fromkeys of <class 'collections.Counter'>> >>> collections.namedtuple <function namedtuple at 0xb6fc4adc> What if change default reprs of classes and functions to just full qualified name module + '.' + qualname (or just qualname if module is builtins)? This will look more neatly. And such reprs are evaluable.

Do you mean like this?

repr(int) => 'int'

repr(int.from_bytes) => 'int.from_bytes'

repr(open) => 'open'

repr(collections.Counter) => 'collections.Counter'

repr(collections.Counter.fromkeys) => 'collections.Counter.fromkeys'

repr(collections.namedtuple) => 'collections.namedtuple'

-1 on that idea.

The suggested repr gives no clue as to what kind of object they are. Are they functions, methods, classes, some kind of Enum-like constant or something special like None? That hurts the usefulness of object reprs at the interactive interpreter. And it leads to weirdness like this:

def spam(x): if not isinstance(x, int): raise TypeError('expected int, got %r' % x)

current behaviour

spam(int) => TypeError: expected int, got <class 'int'>

proposed behaviour

spam(int) => TypeError: expected int, got int

As for them being evaluable, I don't think that's terribly useful. Do you have a use-case for that?

I'm not saying that it will never be useful, but I don't think it is useful enough to make up for the loss of human-readable information (the type of the object). Being able to eval(repr(instance)) is sometimes handy, but I don't think eval(repr(type_or_function)) is useful.

-- Steve



More information about the Python-ideas mailing list