[Python-ideas] Changing str(someclass) to return only the class name
Steven D'Aprano
steve at pearwood.info
Sun Oct 23 07:23:34 CEST 2011
Nick Coghlan wrote:
[...]
> 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.
I believe you are saying that backwards.
The way to get the shorthand display format (i.e. the object's name) is
already to use x.__name__. There's no need for a proposal to bless
x.__name__ as the way to do it since that's already what people do.
This proposal is to bless str(x) (and equivalent forms) as a shorthand
for x.__name__, and *unbless* x.__name__ as the official way to do it. I
expect that's what you mean.
For the avoidance of doubt, this only applies to x a module, function or
class (including built-in types) but not necessarily any other kind of
object.
[...]
> 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.
If this proposal goes ahead, will str(x) => x.__name__ cease to be an
implementation detail and become part of the public API that *must* be
supported by all Python implementations?
(That is not a rhetorical question.)
If not, then other Pythons can return something else and anyone who
cares about writing portable, correct code can't use str(x) as shorthand
and will still need to use x.__name__. str(x) will then be an attractive
nuisance encouraging people to write non-portable code.
But if so, that seems rather heavy-handed to me. str() of every other
kind of object is an implementation detail[1]. Presumably if there were
an Italian Python where str(None) returned "Nessuno", or a Persian
Python where str(2) returned "۲", that would be allowed. I don't see
that classes are special enough to justify making the precise output of
str(cls) part of the public API of classes.
[1] Although it has to be acknowledged that many objects have an obvious
string output that is very unlikely to change.
--
Steven
More information about the Python-ideas
mailing list