[Python-ideas] Changing str(someclass) to return only the class name

Guido van Rossum guido at python.org
Sun Oct 23 04:40:55 CEST 2011


On Sat, Oct 22, 2011 at 3:49 PM, Terry Reedy <tjreedy at 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 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)).

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)



More information about the Python-ideas mailing list