[Python-ideas] Changing str(someclass) to return only the class name
Terry Reedy
tjreedy at udel.edu
Sun Oct 23 00:49:02 CEST 2011
On 10/22/2011 12:35 AM, Guido van Rossum wrote:
> On Fri, Oct 21, 2011 at 9:25 PM, Terry Reedy<tjreedy at 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
More information about the Python-ideas
mailing list