Getting the name of a class

I’m posting this here because the answer wasn’t easy to find — in fact, I got it by guessing.

The problem is: How to get the name of a class as a string — not the class name of an instance, but the name of class object itself.  The answer turns out to be simply the “magic” attribute __name__.  Unfortunately, you can’t see this attribute with dir(), and the Python tutorial section on classes (as of 2.6.4) makes no mention of it.  To be sure, this is not a common use case, but I happened to have one in hand.

>>> from mymodule import User
>>> u = User
>>> u.__class__.__name__
>>> u.__name__
>>> user = u('id')
>>> user.__class__.__name__

, ,