[Python-ideas] Changing str(someclass) to return only the class name
Guido van Rossum
guido at python.org
Tue Oct 25 04:27:46 CEST 2011
On Mon, Oct 24, 2011 at 4:36 PM, Steven D'Aprano <steve at 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.
> Once this change goes ahead, under what circumstances would you expect
> people to continue using cls.__name__ (other than for backwards
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)
More information about the Python-ideas