[Python-ideas] Changing str(someclass) to return only the class name
Steven D'Aprano
steve at pearwood.info
Fri Oct 21 19:45:20 CEST 2011
Éric Araujo wrote:
> Hi everyone,
>
> I’ve sometimes wished that str(someclass) were the natural way to get a
> class name, for example when writing __repr__ methods.
someclass.__name__ seems much more natural to me.
If you want the name of the class, ask for its name, not its string
representation. Generally speaking, the string representation should
tell you what sort of object it is (either explicitly or implicitly),
not just its value.
The same behaviour applies to functions and modules:
>>> import math
>>> str(math)
"<module 'math' from '/usr/local/lib/python3.1/lib-dynload/math.so'>"
>>> def spam():
... pass
...
>>> str(spam)
'<function spam at 0xb7c5726c>'
rather than "math" and "spam" respectively. I would not like str(module)
or str(function) to imitate string objects, and likewise for classes.
They should continue to identify themselves as classes or types:
>>> class K:
... pass
...
>>> str(K)
"<class '__main__.K'>"
> One can say that this change would break code and should thus be
> rejected; one could argue that the previous behavior of str(someclass)
> was undefined, or an implementation detail.
>
> What say you?
-1
--
Steven
More information about the Python-ideas
mailing list