On Sat, Oct 22, 2011 at 2:44 PM, Ben Finney firstname.lastname@example.org wrote:
Guido van Rossum email@example.com writes:
On Sat, Oct 22, 2011 at 1:18 PM, Steven D'Aprano firstname.lastname@example.org 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.
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.
You misunderstood me. I'm not proposing to change the str() of an exception *instance*. That will continue to be the message (while its repr() is a <...> style thing). I'm only proposing to change the str() of an exception *class* -- or any other class, for that matter.
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.
Right, and the built-in types and exceptions are in the same category.
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.
For that you can use repr().