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

Nick Coghlan ncoghlan at gmail.com
Sun Oct 23 03:56:55 CEST 2011


On Sun, Oct 23, 2011 at 7:44 AM, Ben Finney <ben+python at benfinney.id.au> wrote:
> 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.

Until we fix the qualified name problem for nested functions and
classes, there isn't really other information of interest to be
included (and I'm going back on some I said earlier here). While we
*could* include __module__ (especially since class repr's already
include it), it's sometimes actively misleading to do so. By only
including __name__, we deliberately underqualify *everything*, so
"str(cls)" and "str(func)" just refers to the name they were defined
with and omits any additional context.

The current convention is that classes, functions and modules, don't
offer a shorthand "pretty" display format at all. The proposal is to
specifically bless "x.__name__" as an official shorthand. Sure,
sometimes you won't *want* the shorthand, so you'll need to either
explicitly ask for repr(), or otherwise construct your own description
from individual attributes. That's true for a lot of other types as
well (especially when it comes to numbers).

I think the most valid objection raised so far is the fact that some
metaclasses *already* override __str__ to display something other than
the result of type.__repr__(cls). That does have the potential to
cause problems for code dealing with utterly unknown types. However,
such code should likely be explicitly invoking repr() rather than
str() anyway, so this change is unlikely to break anything that isn't
already broken.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list