
I don't think this line of argument is valid. Printing 1 and "1" produces the same output, that's why repr() exists. If someone wants debugging level detail, use repr(), just like the interactive interpreter does. -- Nick Coghlan (via Gmail on Android, so likely to be more terse than usual) On Oct 22, 2011 5:33 PM, "Steven D'Aprano" <steve@pearwood.info> wrote:
Nick Coghlan wrote:
On Sat, Oct 22, 2011 at 3:45 AM, Steven D'Aprano <steve@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.
Yes, I understand the difference between repr and str and the guidelines for them both. My argument is that for human consumption, str(MyClass) should continue to return something like "<class MyClass>" and not just "MyClass".
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.
Regardless of where or how you are using the name, if you explicitly want the name, you should ask for it explicitly rather than implicitly.
Remember also that print(spam) will use str(spam). If you do this:
print(spam) something
what would you expect spam is? My bet is that you expect it to be the string "something". With your suggestion, it could be either the string "something", a function named something, a module named something, or a class named "something" (if one uses __name__ rather than module.class name). I don't consider this helpful.
I am aware that the string representation (using either __str__ or __repr__) of an object is not the definitive word in what the object really is. Using just print, one can't distinguish between a class and a string "<class '__main__.Spam'>", or for that matter between the string 2 and the int 2, and that arbitrary objects can return arbitrary strings. Nevertheless, I like the __str__ of classes, modules and functions just the way they are.
-- Steven
______________________________**_________________ Python-ideas mailing list Python-ideas@python.org http://mail.python.org/**mailman/listinfo/python-ideas<http://mail.python.org/mailman/listinfo/python-ideas>