Why not 3.__class__ ?

Guido van Rossum guido at python.org
Thu Oct 11 15:22:43 EDT 2001


> Here's another example of invoking an attribute on a literal:
> 
> C:\>python
> Python 2.2a1 (#21, Jul 18 2001, 04:25:46) [MSC 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license" for more information.
> >>>
> >>> class Spam: pass
> ...
> >>> s = Spam()
> >>> x = Spam()
> >>>
> >>> isinstance(x,s.__class__)
> 1
> >>> x = 'abc'
> >>> isinstance(x,''.__class__)
> 1
> >>> x = 100
> >>> isinstance(x,0 .__class__)
> 1
> >>>
> 
> If you generally want to know if x is the same kind of instance as y, then
> isinstance(x,y.__class__)
> seems to be a reasonable idiom.
> 
> Given that, it's nice to use the same idiom when y is a builtin type, as in
> isinstance(x,''.__class__)
> isinstance(x,0 .__class__)
> isinstance(x,[].__class__)
> isinstance(x,().__class__)
> isinstance(x,{}.__class__)
> 
> instead of using a second idiom for builtins
> 
> import types
> isinstance(x,types.IntType)
> . . .

I find the ''.__class__ form butt-ugly, and would recommend type('')
instead.  Fortunately, in 2.2 there are built-in names that express
these types much clearer:

isinstance(x, str)
isinstance(x, int)
isinstance(x, list)
isinstance(x, tuple)
isinstance(x, dictionary)

--Guido van Rossum (home page: http://www.python.org/~guido/)




More information about the Python-list mailing list