[Python-ideas] Changing str(someclass) to return only the class name
Nick Coghlan
ncoghlan at gmail.com
Sat Oct 22 02:39:33 CEST 2011
On Sat, Oct 22, 2011 at 3:45 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> É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.
While that's an accurate description of the purpose of a "string
representation", the function that serves that purpose is repr(), not
str(). Éric's patch doesn't touch type.__repr__, only type.__str__.
str() is different - it's the one which is designed for general human
consumption, and may omit some details if it makes sense.
The use case that lead to the patch was actually string interpolation
rather than direct invocation of str(). There's a lot of object
representation code and error message formatting code that currently
uses "obj.__class__.__name__" or "type(obj).__name__" to plug into a
"{}" or "%s" placeholder in a format string.
So I'd actually go the other way and suggest the following change to
only return a subset of the information in the full representations
for all 3 types:
str(module) ==> module.__name__
str(func) ==> func.__name__
str(cls) ==> "{}.{}".format(cls.__module__, cls.__name__) # See note below
Note: nested classes will give misleading information, but they
already do that in their repr() implementations:
>>> def f():
... class C: pass
... return C
...
>>> x = f()
>>> x
<class '__main__.C'>
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas
mailing list