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

Guido van Rossum guido at python.org
Sun Oct 23 04:33:44 CEST 2011


On Sat, Oct 22, 2011 at 4:11 PM, Ron Adam <ron3200 at gmail.com> wrote:
> On Sat, 2011-10-22 at 13:32 -0700, Guido van Rossum wrote:
>> Thinking of str(x) as an API to get a certain value would lead there,
>> yes. But thinking of str(x) as what gets printed by print(x),
>> formatted by "{}.format(x)", and "%s" % s, changes things. 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. Just like
>> print(None) prints 'None', it would make all the sense in the world if
>> print(ZeroDivisionError) printed 'ZeroDivisionError', and
>> print(type(42)) printed 'int'.
>
> I like the part where you say...
>
> "But thinking of str(x) as what gets printed by print(x)"
>
> Which means (to me) that it should be what ever makes the most sense for
> that particular type or object.  For some things, it makes sense to
> return __name__, while for other things, it makes sense to return
> something else.
>
> There isn't a problem unless we are trying to apply a rule to
> *everything*.
>
> Also it should be pointed out that not all objects have a __name__
> attribute.

Correct, and that's why the proposal is strictly limited to changing
str() for classes, functions and modules.

(And I have to agree with Nick that it's best to just return __name__
in all three cases, rather than trying to be clever and use the
qualified name.)

-- 
--Guido van Rossum (python.org/~guido)



More information about the Python-ideas mailing list