Changing str(someclass) to return only the class name

Hi everyone, I’ve sometimes wished that str(someclass) were the natural way to get a class name, for example when writing __repr__ methods. Guido expressed the same wish recently, so I’ve made a patch for Python 3.3. In the whole standard library, only one module (optparse) and three test files (which were parsing the output of str(someclass) or using doctests) had to be updated because of this change: http://bugs.python.org/issue13224 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? Cheers

É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

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. I agree with this rather generally. I'd also like access to the class name, but I don't really like that implementation yet.
A thought: Could this be reframed as a tweak to the reporting of type objects, specifically? If the __repr__ function of a type object returned the desired class information, it seems like it would solve this issue. Currently, print str(type(variable)) # returns a string in the form of #"'module reference and class name' type.__name__ at address" print repr(type(variable)) # returns the same string. print type(variable).__name__ # returns "instance" for any user variable instances. However, if we altered repr to return the qualified name, we'd be pretty much set, as we already have the __name__ variable in type objects* and the __str__ can remain untouched. That would make the information rather easily accessed and without special parsing. (*I'd prefer a short statement to extract that name, too. I could work with "print class(variable)" if the parser could. Other options off the top o' my noggin: "type.name(variable)" or "variable.__name__" where the .__name_ is automatically supplied. (allow overwriting in the class definition?)) -Nate

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. 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@gmail.com | Brisbane, Australia

On 10/21/2011 8:39 PM, Nick Coghlan wrote:
str(module) ==> module.__name__ str(func) ==> func.__name__ str(cls) ==> "{}.{}".format(cls.__module__, cls.__name__) # See note below
If you do this, then also do str(generator) ==> generator.__name__ -- Terry Jan Reedy

On Fri, Oct 21, 2011 at 9:25 PM, Terry Reedy <tjreedy@udel.edu> wrote:
On 10/21/2011 8:39 PM, Nick Coghlan wrote:
str(module) ==> module.__name__ str(func) ==> func.__name__ str(cls) ==> "{}.{}".format(cls.__module__, cls.__name__) # See note below
If you do this, then also do str(generator) ==> generator.__name__
Why? Assuming by "generator" you mean the iteror returned by calling a generator function (not the generator function itself, which is covered by str(func) ==> func.__name__), the generator has no "name" which can be used to retrieve it. The three above (module, function, class) all -- typically -- are referenced by variables whose name is forced by the syntax (import foo, def foo, class foo). But that does not apply to a generator. -- --Guido van Rossum (python.org/~guido)

On 10/22/2011 12:35 AM, Guido van Rossum wrote:
On Fri, Oct 21, 2011 at 9:25 PM, Terry Reedy<tjreedy@udel.edu> wrote:
On 10/21/2011 8:39 PM, Nick Coghlan wrote:
str(module) ==> module.__name__ str(func) ==> func.__name__ str(cls) ==> "{}.{}".format(cls.__module__, cls.__name__) # See note below
If you do this, then also do str(generator) ==> generator.__name__
Why?
For printing messages (which I currently do with failing generators), as you explained in another post: "But thinking of str(x) as what gets printed by print(x), formatted by "{}.format(x)", and "%s" % s, changes things. When I am printing an object and I have no idea what type it is, I'll use repr() or "%r"; but when I know I am printing, say, an exception, I think it would be very nice if print(x) would just print its name."
Assuming by "generator" you mean the iteror returned by calling a generator function (not the generator function itself, which is covered by str(func) ==> func.__name__), the generator has no "name" which can be used to retrieve it. The three above (module, function, class) all -- typically -- are referenced by variables whose name is forced by the syntax (import foo, def foo, class foo). But that does not apply to a generator.
Not relevant unless you want to do something like globals()[str(obj)] or getattr(namespace, str(obj)). The .__name__ attribute of generators is just as much forced by syntax as for the others, as it is a copy of the parent generator function. I am currently +0, as I do not mind occasionally typing .__name__, although I believe it *is* the only exposed __xxx__ name (outside of class statements) in my current code. -- Terry Jan Reedy

On Sat, Oct 22, 2011 at 3:49 PM, Terry Reedy <tjreedy@udel.edu> wrote:
On 10/22/2011 12:35 AM, Guido van Rossum wrote:
On Fri, Oct 21, 2011 at 9:25 PM, Terry Reedy<tjreedy@udel.edu> wrote:
On 10/21/2011 8:39 PM, Nick Coghlan wrote:
str(module) ==> module.__name__ str(func) ==> func.__name__ str(cls) ==> "{}.{}".format(cls.__module__, cls.__name__) # See note below
If you do this, then also do str(generator) ==> generator.__name__
Why?
For printing messages (which I currently do with failing generators), as you explained in another post:
"But thinking of str(x) as what gets printed by print(x), formatted by "{}.format(x)", and "%s" % s, changes things. When I am printing an object and I have no idea what type it is, I'll use repr() or "%r"; but when I know I am printing, say, an exception, I think it would be very nice if print(x) would just print its name."
Assuming by "generator" you mean the iteror returned by calling a generator function (not the generator function itself, which is covered by str(func) ==> func.__name__), the generator has no "name" which can be used to retrieve it. The three above (module, function, class) all -- typically -- are referenced by variables whose name is forced by the syntax (import foo, def foo, class foo). But that does not apply to a generator.
Not relevant unless you want to do something like globals()[str(obj)] or getattr(namespace, str(obj)).
I am totally not following you, but possibly we just are in violent agreement? I don't want to change the str() of a generator object. My reasoning (and this is just intuition) is that printing just the name of the function for a generator object suppresses *too* much information; it would be like printing just the exception (class) name for exception instances. My proposal is not to make str(x) return x.__name__ for everything that happens to have a __name__ attribute (e.g. bound methods also have one). My proposal is to make str(x) return x.__name__ for exactly these three types of objects: modules, classes, and functions.
The .__name__ attribute of generators is just as much forced by syntax as for the others, as it is a copy of the parent generator function.
I am currently +0, as I do not mind occasionally typing .__name__, although I believe it *is* the only exposed __xxx__ name (outside of class statements) in my current code.
-- --Guido van Rossum (python.org/~guido)

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

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>

Nick Coghlan wrote:
If someone wants debugging level detail, use repr(), just like the interactive interpreter does.
I'm just going to repeat what I've said before: explicit is better than implicit. If you want the name of an object (be it a class, a module, a function, or something else), you should explicitly ask for the name, and not rely on its str(). The details returned by str() are, in some sense, arbitrary. The docs describe it as [quote] the “informal” string representation of an object [end quote]. http://docs.python.org/reference/datamodel.html#object.__str__ On that basis, objects are free to return as much, or as little, information as makes sense in their str(). (As you pointed out earlier.) However, the docs also say that str() should return [quote] a string containing a nicely printable representation of an object [end quote]. http://docs.python.org/library/functions.html#str To my mind, the name alone of a class (or function or module) is in no sense a nicely printable representation of the object. I would argue strongly that the property of being "nicely representable" outweighs by far the convenience of avoiding 9 extra characters in one specific use-case: "blah blah blah class '%s'" % cls # instead of cls.__name__ But for the sake of the argument, I'll grant you that we're free to change str(cls) to return the class name, as requested by the OP, or the fully qualified module.class dotted name as suggested by you. So let's suppose that, after a long and bitter debate over which colour to paint this bikeshed, you win the debate. But this doesn't help you at all, because you can't rely on it. It seems to me that the exact format of str(cls) is an implementation detail. You can't rely on other Pythons to do the same thing, nor can you expect a guarantee that str(cls) won't change again in the future. So if you care about the exact string that gets generated, you still have to explicitly use cls.__name__ just as you do now. The __name__ attribute is part of the guaranteed API of class objects (and also functions and modules), the output of str(cls) is not. In my opinion relying on it to return a particular output is dangerous, regardless of whether the output is "<class 'module.MyClass'>", "module.MyClass", "MyClass" or something else. Having str(cls) return just the class name (or the module.class dotted name) is an attractive nuisance that should be resisted. -- Steven

On Sat, Oct 22, 2011 at 1:18 PM, Steven D'Aprano <steve@pearwood.info> wrote:
Nick Coghlan wrote:
If someone wants debugging level detail, use repr(), just like the interactive interpreter does.
I'm just going to repeat what I've said before: explicit is better than implicit. If you want the name of an object (be it a class, a module, a function, or something else), you should explicitly ask for the name, and not rely on its str().
The details returned by str() are, in some sense, arbitrary. The docs describe it as [quote] the “informal” string representation of an object [end quote].
http://docs.python.org/reference/datamodel.html#object.__str__
On that basis, objects are free to return as much, or as little, information as makes sense in their str(). (As you pointed out earlier.)
However, the docs also say that str() should return [quote] a string containing a nicely printable representation of an object [end quote].
http://docs.python.org/library/functions.html#str
To my mind, the name alone of a class (or function or module) is in no sense a nicely printable representation of the object. I would argue strongly that the property of being "nicely representable" outweighs by far the convenience of avoiding 9 extra characters in one specific use-case:
"blah blah blah class '%s'" % cls # instead of cls.__name__
But for the sake of the argument, I'll grant you that we're free to change str(cls) to return the class name, as requested by the OP, or the fully qualified module.class dotted name as suggested by you. So let's suppose that, after a long and bitter debate over which colour to paint this bikeshed, you win the debate.
But this doesn't help you at all, because you can't rely on it. It seems to me that the exact format of str(cls) is an implementation detail. You can't rely on other Pythons to do the same thing, nor can you expect a guarantee that str(cls) won't change again in the future. So if you care about the exact string that gets generated, you still have to explicitly use cls.__name__ just as you do now.
The __name__ attribute is part of the guaranteed API of class objects (and also functions and modules), the output of str(cls) is not. In my opinion relying on it to return a particular output is dangerous, regardless of whether the output is "<class 'module.MyClass'>", "module.MyClass", "MyClass" or something else.
Having str(cls) return just the class name (or the module.class dotted name) is an attractive nuisance that should be resisted.
Thinking of str(x) as an API to get a certain value would lead there, yes. But thinking of str(x) as what gets printed by print(x), formatted by "{}.format(x)", and "%s" % s, changes things. When I am printing an object and I have no idea what type it is, I'll use repr() or "%r"; but when I know I am printing, say, an exception, I think it would be very nice if print(x) would just print its name. Just like print(None) prints 'None', it would make all the sense in the world if print(ZeroDivisionError) printed 'ZeroDivisionError', and print(type(42)) printed 'int'. -- --Guido van Rossum (python.org/~guido)

On 10/22/11 22:32, Guido van Rossum wrote:
Thinking of str(x) as an API to get a certain value would lead there, yes. But thinking of str(x) as what gets printed by print(x), formatted by "{}.format(x)", and "%s" % s, changes things. When I am printing an object and I have no idea what type it is, I'll use repr() or "%r"; but when I know I am printing, say, an exception, I think it would be very nice if print(x) would just print its name. Just like print(None) prints 'None', it would make all the sense in the world if print(ZeroDivisionError) printed 'ZeroDivisionError', and print(type(42)) printed 'int'.
+1. Georg

Guido van Rossum <guido@python.org> writes:
On Sat, Oct 22, 2011 at 1:18 PM, Steven D'Aprano <steve@pearwood.info> wrote:
I'm just going to repeat what I've said before: explicit is better than implicit. If you want the name of an object (be it a class, a module, a function, or something else), you should explicitly ask for the name, and not rely on its str().
+1. Many objects, specifically including exceptions, have something more useful than the name to return from ‘str(x)’.
However, the docs also say that str() should return [quote] a string containing a nicely printable representation of an object [end quote].
Yes. The name of an object (if it has one) is often just one part of the representation of an object.
Having str(cls) return just the class name (or the module.class dotted name) is an attractive nuisance that should be resisted.
Agreed.
When I am printing an object and I have no idea what type it is, I'll use repr() or "%r"; but when I know I am printing, say, an exception, I think it would be very nice if print(x) would just print its name.
−1. That makes the string representation of an exception much less useful. Exceptions don't have names; each exception *type* has a name, but that doesn't distinguish instances of the type from one another. When there is an ‘IOError’ it's far more useful that the string representation contains the exception *message*, since the name of the exception type doesn't tell the user much about what went wrong.
Just like print(None) prints 'None', it would make all the sense in the world if print(ZeroDivisionError) printed 'ZeroDivisionError'
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. -- \ “Ignorance more frequently begets confidence than does | `\ knowledge.” —Charles Darwin, _The Descent of Man_, 1871 | _o__) | Ben Finney

On Sun, Oct 23, 2011 at 7:44 AM, Ben Finney <ben+python@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@gmail.com | Brisbane, Australia

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

On Sat, Oct 22, 2011 at 10:23 PM, Steven D'Aprano <steve@pearwood.info> wrote:
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.
That is putting words in my mouth. There's no intent to unbless x.__name__, period. Also, there's no intent to bless str(x) as x.__name__ if you want the name. The only intent is to make what gets printed if you print a function, class or module to be less verbose.
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.)
str() is never an implementation detail. The expectation is that str() is roughly compatible on different Python implementations. If it was an implementation detail, I wouldn't have sustained this discussion for so long, I'd just committed the change. At the same time I see no reason for other implementations not to follow CPython for this particular proposal, and if they disagree they should argue here, not refuse to implement the change.
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.
I assume that people will continue to understand that str()'s contract is weak -- it produces a pretty string. The only place where its contract is stronger is for some specific types, like str itself (str() of a string is that string itself, period) and for integers and floats (a decimal representation). We're not changing the strength of the contract here. We're just making it prettier.
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.
It seems to me you are reading too much into the proposal. Please back down. The sky is not falling.
[1] Although it has to be acknowledged that many objects have an obvious string output that is very unlikely to change.
-- --Guido van Rossum (python.org/~guido)

One advantage of the way it works now is that if you have a class, function or module when you're not expecting it, print tells you what's going on. Compare these:
print('9'.isdigit) isdigit
vs
print('9'.isdigit) <built-in method isdigit of str object at 0x01D5A038>
--- Bruce

On Sun, Oct 23, 2011 at 11:37 AM, Bruce Leban <bruce@leapyear.org> wrote:
One advantage of the way it works now is that if you have a class, function or module when you're not expecting it, print tells you what's going on. Compare these:
print('9'.isdigit) isdigit
vs
print('9'.isdigit) <built-in method isdigit of str object at 0x01D5A038>
Fortunately, that particular example won't change, because '9'.isdigit is not a function -- it is a bound method. They're different object types. -- --Guido van Rossum (python.org/~guido)

Guido van Rossum wrote:
On Sat, Oct 22, 2011 at 10:23 PM, Steven D'Aprano <steve@pearwood.info> wrote:
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.
That is putting words in my mouth. There's no intent to unbless x.__name__, period. Also, there's no intent to bless str(x) as x.__name__ if you want the name. The only intent is to make what gets printed if you print a function, class or module to be less verbose.
I'm sorry about that, I was describing the proposal as best I understood it. Once this change goes ahead, under what circumstances would you expect people to continue using cls.__name__ (other than for backwards compatibility)? When beginners ask me "how do I get the name of a class?", what answer should I give? For example, I have code that does things like this: raise TypeError('expected a string but got %s' % type(arg).__name__) In the future, I expect that should be written like this: raise TypeError('expected a string but got %s' % type(arg)) That's all I meant by "unbless". I didn't mean to imply that __name__ would go away, only that it would cease to be the One Obvious Way to get the name. If I'm wrong about this, then I'm genuinely confused and don't understand the motivation for this change. -- Steven

On Tue, 2011-10-25 at 10:36 +1100, Steven D'Aprano wrote:
Guido van Rossum wrote:
On Sat, Oct 22, 2011 at 10:23 PM, Steven D'Aprano <steve@pearwood.info> wrote:
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.
That is putting words in my mouth. There's no intent to unbless x.__name__, period. Also, there's no intent to bless str(x) as x.__name__ if you want the name. The only intent is to make what gets printed if you print a function, class or module to be less verbose.
I'm sorry about that, I was describing the proposal as best I understood it.
Once this change goes ahead, under what circumstances would you expect people to continue using cls.__name__ (other than for backwards compatibility)? When beginners ask me "how do I get the name of a class?", what answer should I give?
This isn't a big as change as you may be thinking of. name = cls.__name__ Won't change. You will still need to use the __name__ attribute to get a name in almost all situations except for when you want to place the name in a string or print it, you can then use just the cls, as the __str__ method would do the rest for you.
For example, I have code that does things like this:
raise TypeError('expected a string but got %s' % type(arg).__name__)
In the future, I expect that should be written like this:
raise TypeError('expected a string but got %s' % type(arg))
Yes, it could be written that way, but it's not required.
That's all I meant by "unbless". I didn't mean to imply that __name__ would go away, only that it would cease to be the One Obvious Way to get the name. If I'm wrong about this, then I'm genuinely confused and don't understand the motivation for this change.
Printing the name of an exception, class, or function, is very common for logging and error messages, and this makes that easier and cleaner. And if a repr is wanted, we still have that also. Cheers, Ron

On Mon, Oct 24, 2011 at 4:36 PM, Steven D'Aprano <steve@pearwood.info> wrote:
Guido van Rossum wrote:
That is putting words in my mouth. There's no intent to unbless x.__name__, period. Also, there's no intent to bless str(x) as x.__name__ if you want the name. The only intent is to make what gets printed if you print a function, class or module to be less verbose.
I'm sorry about that, I was describing the proposal as best I understood it.
Okay.
Once this change goes ahead, under what circumstances would you expect people to continue using cls.__name__ (other than for backwards compatibility)?
Whenever they want to know what the name is, use the name to look something up, to compare it to a list of known names, you name it...
When beginners ask me "how do I get the name of a class?", what answer should I give?
Use .__name__, definitely.
For example, I have code that does things like this:
raise TypeError('expected a string but got %s' % type(arg).__name__)
In the future, I expect that should be written like this:
raise TypeError('expected a string but got %s' % type(arg))
Yes, because here the point is to quickly put some useful info in a message. Likely the code *already* looks like the second form and we've just made it prettier.
That's all I meant by "unbless". I didn't mean to imply that __name__ would go away, only that it would cease to be the One Obvious Way to get the name. If I'm wrong about this, then I'm genuinely confused and don't understand the motivation for this change.
Depends on what you want to do with it. If you're just showing it to a user, str() is your friend. If you want to compute with it, parse it, etc., use .__name__. You may think this violates TOOWTDI, but as I've said before, that was a white lie (as well a cheeky response to Perl's slogan around 2000). Being able to express intent (to human readers) often requires choosing between multiple forms that do essentially the same thing, but look different to the reader. -- --Guido van Rossum (python.org/~guido)

On Oct 24, 2011, at 4:27 PM, Guido van Rossum wrote:
You may think this violates TOOWTDI, but as I've said before, that was a white lie (as well a cheeky response to Perl's slogan around 2000). Being able to express intent (to human readers) often requires choosing between multiple forms that do essentially the same thing, but look different to the reader.
So, you're saying TMTOWTDI and "different things should look different"? Someone send a letter of surrender to Larry Wall. ;-)

On Sat, Oct 22, 2011 at 2:44 PM, Ben Finney <ben+python@benfinney.id.au> wrote:
Guido van Rossum <guido@python.org> writes:
On Sat, Oct 22, 2011 at 1:18 PM, Steven D'Aprano <steve@pearwood.info> wrote:
I'm just going to repeat what I've said before: explicit is better than implicit. If you want the name of an object (be it a class, a module, a function, or something else), you should explicitly ask for the name, and not rely on its str().
+1. Many objects, specifically including exceptions, have something more useful than the name to return from 'str(x)'.
However, the docs also say that str() should return [quote] a string containing a nicely printable representation of an object [end quote].
Yes. The name of an object (if it has one) is often just one part of the representation of an object.
Having str(cls) return just the class name (or the module.class dotted name) is an attractive nuisance that should be resisted.
Agreed.
When I am printing an object and I have no idea what type it is, I'll use repr() or "%r"; but when I know I am printing, say, an exception, I think it would be very nice if print(x) would just print its name.
-1. That makes the string representation of an exception much less useful.
Exceptions don't have names; each exception *type* has a name, but that doesn't distinguish instances of the type from one another. When there is an 'IOError' it's far more useful that the string representation contains the exception *message*, since the name of the exception type doesn't tell the user much about what went wrong.
You misunderstood me. I'm not proposing to change the str() of an exception *instance*. That will continue to be the message (while its repr() is a <...> style thing). I'm only proposing to change the str() of an exception *class* -- or any other class, for that matter.
Just like print(None) prints 'None', it would make all the sense in the world if print(ZeroDivisionError) printed 'ZeroDivisionError'
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.
Right, and the built-in types and exceptions are in the same category.
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.
For that you can use repr(). -- --Guido van Rossum (python.org/~guido)

Guido van Rossum <guido@python.org> writes:
On Sat, Oct 22, 2011 at 2:44 PM, Ben Finney <ben+python@benfinney.id.au> wrote:
Guido van Rossum <guido@python.org> writes:
When I am printing an object and I have no idea what type it is, I'll use repr() or "%r"; but when I know I am printing, say, an exception, I think it would be very nice if print(x) would just print its name.
-1. That makes the string representation of an exception much less useful.
Exceptions don't have names; each exception *type* has a name, but that doesn't distinguish instances of the type from one another. When there is an 'IOError' it's far more useful that the string representation contains the exception *message*, since the name of the exception type doesn't tell the user much about what went wrong.
You misunderstood me. I'm not proposing to change the str() of an exception *instance*.
That's what I take to be the meaning of “print an exception”. Like “print an int” or “print a list”, it seems to me that refers not to a type, but to an instance of the type. Thanks for clarifying that you meant “print an exception class”. -- \ “I wish there was a knob on the TV to turn up the intelligence. | `\ There's a knob called ‘brightness’ but it doesn't work.” | _o__) —Eugene P. Gallagher | Ben Finney

On Sat, Oct 22, 2011 at 11:58 PM, Ben Finney <ben+python@benfinney.id.au> wrote:
Guido van Rossum <guido@python.org> writes:
On Sat, Oct 22, 2011 at 2:44 PM, Ben Finney <ben+python@benfinney.id.au> wrote:
Guido van Rossum <guido@python.org> writes:
When I am printing an object and I have no idea what type it is, I'll use repr() or "%r"; but when I know I am printing, say, an exception, I think it would be very nice if print(x) would just print its name.
-1. That makes the string representation of an exception much less useful.
Exceptions don't have names; each exception *type* has a name, but that doesn't distinguish instances of the type from one another. When there is an 'IOError' it's far more useful that the string representation contains the exception *message*, since the name of the exception type doesn't tell the user much about what went wrong.
You misunderstood me. I'm not proposing to change the str() of an exception *instance*.
That's what I take to be the meaning of “print an exception”. Like “print an int” or “print a list”, it seems to me that refers not to a type, but to an instance of the type.
Thanks for clarifying that you meant “print an exception class”.
Sorry, reading back what I wrote with less context it's clear how you could misread it. Since the proposal clearly started out limited to classes, functions and modules, the ambiguity never occurred to me. -- --Guido van Rossum (python.org/~guido)

On Sat, 2011-10-22 at 13:32 -0700, Guido van Rossum wrote:
Thinking of str(x) as an API to get a certain value would lead there, yes. But thinking of str(x) as what gets printed by print(x), formatted by "{}.format(x)", and "%s" % s, changes things. When I am printing an object and I have no idea what type it is, I'll use repr() or "%r"; but when I know I am printing, say, an exception, I think it would be very nice if print(x) would just print its name. Just like print(None) prints 'None', it would make all the sense in the world if print(ZeroDivisionError) printed 'ZeroDivisionError', and print(type(42)) printed 'int'.
I like the part where you say... "But thinking of str(x) as what gets printed by print(x)" Which means (to me) that it should be what ever makes the most sense for that particular type or object. For some things, it makes sense to return __name__, while for other things, it makes sense to return something else. There isn't a problem unless we are trying to apply a rule to *everything*. Also it should be pointed out that not all objects have a __name__ attribute. Cheers, Ron

On Sat, Oct 22, 2011 at 4:11 PM, Ron Adam <ron3200@gmail.com> wrote:
On Sat, 2011-10-22 at 13:32 -0700, Guido van Rossum wrote:
Thinking of str(x) as an API to get a certain value would lead there, yes. But thinking of str(x) as what gets printed by print(x), formatted by "{}.format(x)", and "%s" % s, changes things. When I am printing an object and I have no idea what type it is, I'll use repr() or "%r"; but when I know I am printing, say, an exception, I think it would be very nice if print(x) would just print its name. Just like print(None) prints 'None', it would make all the sense in the world if print(ZeroDivisionError) printed 'ZeroDivisionError', and print(type(42)) printed 'int'.
I like the part where you say...
"But thinking of str(x) as what gets printed by print(x)"
Which means (to me) that it should be what ever makes the most sense for that particular type or object. For some things, it makes sense to return __name__, while for other things, it makes sense to return something else.
There isn't a problem unless we are trying to apply a rule to *everything*.
Also it should be pointed out that not all objects have a __name__ attribute.
Correct, and that's why the proposal is strictly limited to changing str() for classes, functions and modules. (And I have to agree with Nick that it's best to just return __name__ in all three cases, rather than trying to be clever and use the qualified name.) -- --Guido van Rossum (python.org/~guido)

Le 23/10/2011 04:33, Guido van Rossum a écrit :
(And I have to agree with Nick that it's best to just return __name__ in all three cases, rather than trying to be clever and use the qualified name.)
My first reaction was that returning 'module.name' was more helpful and saved more typing than just 'name', but I don’t have any real arguments. I will update the patch on http://bugs.python.org/issue13224 to change the repr of functions and modules. People concerned about breakage will be able to compile a patched Python to test their code. Cheers

On 22 October 2011 21:32, Guido van Rossum <guido@python.org> wrote:
Nick Coghlan wrote:
If someone wants debugging level detail, use repr(), just like the interactive interpreter does.
I'm just going to repeat what I've said before: explicit is better than implicit. If you want the name of an object (be it a class, a module, a function, or something else), you should explicitly ask for the name, and not rely on its str().
The details returned by str() are, in some sense, arbitrary. The docs describe it as [quote] the “informal” string representation of an object [end quote].
http://docs.python.org/reference/datamodel.html#object.__str__
On that basis, objects are free to return as much, or as little, information as makes sense in their str(). (As you pointed out earlier.)
However, the docs also say that str() should return [quote] a string containing a nicely printable representation of an object [end quote].
http://docs.python.org/library/functions.html#str
To my mind, the name alone of a class (or function or module) is in no sense a nicely printable representation of the object. I would argue strongly
On Sat, Oct 22, 2011 at 1:18 PM, Steven D'Aprano <steve@pearwood.info> wrote: that
the property of being "nicely representable" outweighs by far the convenience of avoiding 9 extra characters in one specific use-case:
"blah blah blah class '%s'" % cls # instead of cls.__name__
But for the sake of the argument, I'll grant you that we're free to change str(cls) to return the class name, as requested by the OP, or the fully qualified module.class dotted name as suggested by you. So let's suppose that, after a long and bitter debate over which colour to paint this bikeshed, you win the debate.
But this doesn't help you at all, because you can't rely on it. It seems to me that the exact format of str(cls) is an implementation detail. You can't rely on other Pythons to do the same thing, nor can you expect a guarantee that str(cls) won't change again in the future. So if you care about the exact string that gets generated, you still have to explicitly use cls.__name__ just as you do now.
The __name__ attribute is part of the guaranteed API of class objects (and also functions and modules), the output of str(cls) is not. In my opinion relying on it to return a particular output is dangerous, regardless of whether the output is "<class 'module.MyClass'>", "module.MyClass", "MyClass" or something else.
Having str(cls) return just the class name (or the module.class dotted name) is an attractive nuisance that should be resisted.
Thinking of str(x) as an API to get a certain value would lead there, yes. But thinking of str(x) as what gets printed by print(x), formatted by "{}.format(x)", and "%s" % s, changes things. When I am printing an object and I have no idea what type it is, I'll use repr() or "%r"; but when I know I am printing, say, an exception, I think it would be very nice if print(x) would just print its name. Just like print(None) prints 'None', it would make all the sense in the world if print(ZeroDivisionError) printed 'ZeroDivisionError', and print(type(42)) printed 'int'.
+1 Michael
-- --Guido van Rossum (python.org/~guido <http://python.org/%7Eguido>) _______________________________________________ Python-ideas mailing list Python-ideas@python.org http://mail.python.org/mailman/listinfo/python-ideas
-- http://www.voidspace.org.uk/ May you do good and not evil May you find forgiveness for yourself and forgive others May you share freely, never taking more than you give. -- the sqlite blessing http://www.sqlite.org/different.html

Hi, Le 22/10/2011 22:18, Steven D'Aprano a écrit :
I'm just going to repeat what I've said before: explicit is better than implicit. If you want the name of an object (be it a class, a module, a function, or something else), you should explicitly ask for the name, and not rely on its str().
[...]
But for the sake of the argument, I'll grant you that we're free to change str(cls) to return the class name, as requested by the OP, or the fully qualified module.class dotted name as suggested by you. So let's suppose that, after a long and bitter debate over which colour to paint this bikeshed, you win the debate.
Hm. Sometimes we want the class name, sometimes module.class, so even with the change we won’t always be able to use str(cls).
But this doesn't help you at all, because you can't rely on it. It seems to me that the exact format of str(cls) is an implementation detail. You can't rely on other Pythons to do the same thing, nor can you expect a guarantee that str(cls) won't change again in the future. So if you care about the exact string that gets generated, you still have to explicitly use cls.__name__ just as you do now.
This is a very good point. The output of repr and str is not (TTBOMK) exactly defined or guaranteed; nonetheless, I expect that many people (including me) rely on some conversions (like the fact that repr('somestr') includes quotes). So we can change str(cls) and say that *now* it has defined output, or leave it alone to avoid breaking code that does depend on the output, which can be seen as a wrong thing or a pragmatic thing (“I need it and it works”). Regards

On Fri, Oct 28, 2011 at 9:15 AM, Éric Araujo <merwok@netwok.org> wrote:
Le 22/10/2011 22:18, Steven D'Aprano a écrit :
I'm just going to repeat what I've said before: explicit is better than implicit. If you want the name of an object (be it a class, a module, a function, or something else), you should explicitly ask for the name, and not rely on its str().
[...]
But for the sake of the argument, I'll grant you that we're free to change str(cls) to return the class name, as requested by the OP, or the fully qualified module.class dotted name as suggested by you. So let's suppose that, after a long and bitter debate over which colour to paint this bikeshed, you win the debate.
Hm. Sometimes we want the class name, sometimes module.class, so even with the change we won’t always be able to use str(cls).
It is a well-known fact of humanity that you can't please anyone. There's not that much data on how often the full name is better; my hunch however is that most of the time the class name is sufficiently unique within the universe of classes that could be printed, and showing the module name just feels pedantic. Apps that know just the name is sub-optimal should stick to rendering using cls.__module__ and cls.__name__.
But this doesn't help you at all, because you can't rely on it. It seems to me that the exact format of str(cls) is an implementation detail. You can't rely on other Pythons to do the same thing, nor can you expect a guarantee that str(cls) won't change again in the future. So if you care about the exact string that gets generated, you still have to explicitly use cls.__name__ just as you do now.
This is a very good point.
The output of repr and str is not (TTBOMK) exactly defined or guaranteed; nonetheless, I expect that many people (including me) rely on some conversions (like the fact that repr('somestr') includes quotes). So we can change str(cls) and say that *now* it has defined output, or leave it alone to avoid breaking code that does depend on the output, which can be seen as a wrong thing or a pragmatic thing (“I need it and it works”).
In my view, str() and repr() are both for human consumption (though in somewhat different contexts). If tweaking them helps humans understand the output better then let's tweak them. If you as a developer feel particularly anal about how you want your object printed, you should avoid repr() or str() and write your own formatting function. If as a programmer you feel the urge to go parse the output of repr() or str(), you should always *know* that a future version of Python can break your code, and you should file a feature request to have an API added to the class so you won't have to parse the repr() or str(). -- --Guido van Rossum (python.org/~guido)

Hi there, I get that repr() is supposed to be the precise representation and str() is intended more to be friendly than precise. My concern with the proposal is just that this: >>> print x foo ...doesn't actually feel that friendly to me. I want to know that it's *probably* a function or *probably* a class, the same way that today, when I see: >>> print x biscuit >>> print y [1, 2, 3] I can guess that x is *probably* a string and y is *probably* a list (e.g. because I know I'm not working with any custom objects whose __str__ returns those things). It would create a slightly higher mental burden (or slightly higher probability of human error) if, when I see: >>> print x Splat ...I have to remember that x might be a string or a function or a class. I'd just like some kind of visual hint as to what it is. Like: >>> print x foo() or: >>> print x function foo or: >>> print x function foo(a, b) or: >>> print x class Bar In fact "function foo(a, b)" would actually be rather useful in a lot of situations, and I would argue, friendlier than "foo". --Ping

Ka-Ping Yee wrote:
I'd just like some kind of visual hint as to what it is. Like:
>>> print x foo()
or:
>>> print x function foo
or:
>>> print x function foo(a, b)
or:
>>> print x class Bar
In fact "function foo(a, b)" would actually be rather useful in a lot of situations, and I would argue, friendlier than "foo".
+1 If we're gonna make a change, let's make it a great one. :) ~Ethan~

On Oct 28, 2011, at 03:00 PM, Ka-Ping Yee wrote:
>>> print x foo
...doesn't actually feel that friendly to me. I want to know that it's *probably* a function or *probably* a class
>>> print x None What is x? :) -Barry

-1. I'd like it so that (given a suitable set of imports) if you typed back to the interpreter what it printed at you, you get the same thing back again.
print(x) 42 print(42) 42 print(y) None print(None) None print(z) foo print(foo) foo
Ping's proposal would goes against this:
print(x) foo() print(foo()) 42 print(Splat) class Splat print(class Splat) SyntaxError: invalid syntax
I'm expecting that in most cases there is enough redundancy in the name that you'll know what kind of thing it is. And if you want to know for sure, continue to use repr() -- or, at the interactive prompt, just omit the print() call, since the interactive interpreter automatically calls repr() on your expression. --Guido On Fri, Oct 28, 2011 at 3:00 PM, Ka-Ping Yee <python@zesty.ca> wrote:
Hi there,
I get that repr() is supposed to be the precise representation and str() is intended more to be friendly than precise. My concern with the proposal is just that this:
>>> print x foo
...doesn't actually feel that friendly to me. I want to know that it's *probably* a function or *probably* a class, the same way that today, when I see:
>>> print x biscuit
>>> print y [1, 2, 3]
I can guess that x is *probably* a string and y is *probably* a list (e.g. because I know I'm not working with any custom objects whose __str__ returns those things).
It would create a slightly higher mental burden (or slightly higher probability of human error) if, when I see:
>>> print x Splat
...I have to remember that x might be a string or a function or a class.
I'd just like some kind of visual hint as to what it is. Like:
>>> print x foo()
or:
>>> print x function foo
or:
>>> print x function foo(a, b)
or:
>>> print x class Bar
In fact "function foo(a, b)" would actually be rather useful in a lot of situations, and I would argue, friendlier than "foo".
--Ping
-- --Guido van Rossum (python.org/~guido)

On 10/28/2011 1:51 PM, Guido van Rossum wrote:
In my view, str() and repr() are both for human consumption (though in somewhat different contexts). If tweaking them helps humans understand the output better then let's tweak them.
With that explanation, I am fine with whatever you decide. Without expensive study, 'human friendliness' is ultimately a judgment call.
If you as a developer feel particularly anal about how you want your object printed, you should avoid repr() or str() and write your own formatting function.
The only guarantee in the str doc is that str(astring) is astring. (The repr doc says much more, but you are not currently proposing to change that.) With that guarantee, users have complete control of output. When comparing actual to expected strings, I should and will continue using .__name__ and .format().
If as a programmer you feel the urge to go parse the output of repr() or str(), you should always *know* that a future version of Python can break your code,
doctest is known to be fragile and has gimmicks already to avoid breakage. That tail should not wag the dog.
and you should file a feature request to have an API added to the class so you won't have to parse the repr() or str().
I agree that classes should make all vital info available as Python objects that one can compute with. A similar issue came on the tracker with the suggestion that the dis module should gain a computation friendly interface to return the objects that currently get formatted into each line. -- Terry Jan Reedy

Hi, Le 28/10/2011 19:51, Guido van Rossum a écrit :
On Fri, Oct 28, 2011 at 9:15 AM, Éric Araujo <merwok@netwok.org> wrote:
Hm. Sometimes we want the class name, sometimes module.class, so even with the change we won’t always be able to use str(cls). It is a well-known fact of humanity that you can't please anyone. There's not that much data on how often the full name is better; my hunch however is that most of the time the class name is sufficiently unique within the universe of classes that could be printed, and showing the module name just feels pedantic. Apps that know just the name is sub-optimal should stick to rendering using cls.__module__ and cls.__name__.
Fair enough.
The output of repr and str is not (TTBOMK) exactly defined or guaranteed; nonetheless, I expect that many people (including me) rely on some conversions (like the fact that repr('somestr') includes quotes). So we can change str(cls) and say that *now* it has defined output, or leave it alone to avoid breaking code that does depend on the output, which can be seen as a wrong thing or a pragmatic thing (“I need it and it works”). In my view, str() and repr() are both for human consumption (though in somewhat different contexts). If tweaking them helps humans understand the output better then let's tweak them. If you as a developer feel particularly anal about how you want your object printed, you should avoid repr() or str() and write your own formatting function.
If as a programmer you feel the urge to go parse the output of repr() or str(), you should always *know* that a future version of Python can break your code, and you should file a feature request to have an API added to the class so you won't have to parse the repr() or str().
Okay! I will update the patch to change str(func) and str(module). As it’s a debugging aid meant for human, I won’t update the doc or stdlib to recommend using str(x) instead of x.__name__ and everyone should be happy (or complain before the final release). Cheers

On Mon, 31 Oct 2011 10:10:28 -0700 Ethan Furman <ethan@stoneleaf.us> wrote:
Guido van Rossum wrote:
In my view, str() and repr() are both for human consumption
I was under the impression that repr() was for eval consumption (when possible).
Only for basic types. repr() is generally not eval()-able. Regards Antoine.

On Sat, 22 Oct 2011 18:32:25 +1100 Steven D'Aprano <steve@pearwood.info> wrote:
Remember also that print(spam) will use str(spam). If you do this:
print(spam) something
what would you expect spam is?
What if:
print(spam) 1
It might be the integer 1 or the string "1". You need repr() to tell the difference. Regards Antoine.

On 22 October 2011 22:33, Antoine Pitrou <solipsis@pitrou.net> wrote:
On Sat, 22 Oct 2011 18:32:25 +1100 Steven D'Aprano <steve@pearwood.info> wrote:
Remember also that print(spam) will use str(spam). If you do this:
>>> print(spam) something
what would you expect spam is?
What if:
print(spam) 1
It might be the integer 1 or the string "1". You need repr() to tell the difference.
Indeed:
print(A) <class '__main__.A'> A "<class '__main__.A'>"
-- Arnaud

Antoine Pitrou wrote: [...]
It might be the integer 1 or the string "1". You need repr() to tell the difference.
Antoine, that's a cheap shot. The *very next paragraph* of my post which you replied to, and which you snipped out of your response, says: 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. Can we please stop throwing up this red herring? Uniqueness of the str() or repr() of an object is not and has never been a requirement, which is fortunate since it is physically impossible. -- Steven

On 10/23/11 06:26, Steven D'Aprano wrote:
Antoine Pitrou wrote: [...]
It might be the integer 1 or the string "1". You need repr() to tell the difference.
Antoine, that's a cheap shot. The *very next paragraph* of my post which you replied to, and which you snipped out of your response, says:
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.
Can we please stop throwing up this red herring?
Well, if you stop throwing the red herring of "but you can't decide between strings and classes anymore". By your own quote you're now down to "but I like it the way it is", which is fine as a -1 in the "voting", but please don't make it seem like you have subjective arguments. Georg

On 2011-10-23, at 11:27 , Georg Brandl wrote:
Well, if you stop throwing the red herring of "but you can't decide between strings and classes anymore".
By your own quote you're now down to "but I like it the way it is", which is fine as a -1 in the "voting", but please don't make it seem like you have subjective arguments.
Shouldn't the second to last word be "objective"? "I like the current one best" sounds like a subjective argument to me.

On 10/23/11 11:27, Georg Brandl wrote:
On 10/23/11 06:26, Steven D'Aprano wrote:
Antoine Pitrou wrote: [...]
It might be the integer 1 or the string "1". You need repr() to tell the difference.
Antoine, that's a cheap shot. The *very next paragraph* of my post which you replied to, and which you snipped out of your response, says:
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.
Can we please stop throwing up this red herring?
Well, if you stop throwing the red herring of "but you can't decide between strings and classes anymore".
By your own quote you're now down to "but I like it the way it is", which is fine as a -1 in the "voting", but please don't make it seem like you have subjective arguments.
s/subjective/objective/, of course :) Georg

On Sun, 23 Oct 2011 15:26:16 +1100 Steven D'Aprano <steve@pearwood.info> wrote:
Antoine Pitrou wrote: [...]
It might be the integer 1 or the string "1". You need repr() to tell the difference.
Antoine, that's a cheap shot. The *very next paragraph* of my post which you replied to, and which you snipped out of your response, says:
Woops, sorry, I had missed it :( Regards Antoine.
participants (18)
-
Antoine Pitrou
-
Arnaud Delobelle
-
Barry Warsaw
-
Ben Finney
-
Bruce Leban
-
Carl M. Johnson
-
Ethan Furman
-
Georg Brandl
-
Guido van Rossum
-
Ka-Ping Yee
-
Masklinn
-
Michael Foord
-
Nick Coghlan
-
Ron Adam
-
Spectral One
-
Steven D'Aprano
-
Terry Reedy
-
Éric Araujo