[Python-ideas] Changing str(someclass) to return only the class name

Ben Finney ben+python at benfinney.id.au
Sat Oct 22 23:44:24 CEST 2011


Guido van Rossum <guido at python.org> writes:

> On Sat, Oct 22, 2011 at 1:18 PM, Steven D'Aprano <steve at pearwood.info> wrote:

> > I'm just going to repeat what I've said before: explicit is better
> > than implicit. If you want the name of an object (be it a class, a
> > module, a function, or something else), you should explicitly ask
> > for the name, and not rely on its str().

+1. Many objects, specifically including exceptions, have something more
useful than the name to return from ‘str(x)’.

> > However, the docs also say that str() should return [quote] a string
> > containing a nicely printable representation of an object [end
> > quote].

Yes. The name of an object (if it has one) is often just one part of the
representation of an object.

> > Having str(cls) return just the class name (or the module.class
> > dotted name) is an attractive nuisance that should be resisted.

Agreed.

> When I am printing an object and I have no idea what type it is, I'll
> use repr() or "%r"; but when I know I am printing, say, an exception,
> I think it would be very nice if print(x) would just print its name.

−1. That makes the string representation of an exception much less
useful.

Exceptions don't have names; each exception *type* has a name, but that
doesn't distinguish instances of the type from one another. When there
is an ‘IOError’ it's far more useful that the string representation
contains the exception *message*, since the name of the exception type
doesn't tell the user much about what went wrong.

> Just like print(None) prints 'None', it would make all the sense in
> the world if print(ZeroDivisionError) printed 'ZeroDivisionError'

Those examples are objects which are effectively identical in each
instance. (In the case of None, there is only one instance). Those are
the unusual case; the common case is that objects of a given type are
different form each other, and that frequently means their printable
representation should be different too.

If the instances have a name (e.g. function objects), I agree the name
should be *included in* the string representation. But there's usually
other useful information that should also be included.

-- 
 \              “Ignorance more frequently begets confidence than does |
  `\           knowledge.” —Charles Darwin, _The Descent of Man_, 1871 |
_o__)                                                                  |
Ben Finney




More information about the Python-ideas mailing list