Why not 3.__class__ ?

James_Althoff at i2.com James_Althoff at i2.com
Thu Oct 11 14:30:47 EDT 2001


Guido van Rossum wrote:
>Marcin, I don't understand why you care so much about being able to
>write 3.foo.  It's painful to fix in the lexer, and probably leads to
>less useful error messages if someone makes a mistake in a float
>literal (e.g. "3.e 0").  And I see zero use for it: in practice, you
>will never ask for 3.foo -- you'll ask for x.foo where x happens to
?contain the value 3.

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)
. . .

A second negative against the latter idiom: our experience with Jython has
been saddled with significant performance issues doing imports.  Generally,
we try to avoid unnecessary imports whenever possible.

At a higher level it seems that if you want to do an "isinstance" test, it
is nicer to use the class object that you already have "in hand" (or can
easily get to with a literal constant) rather than having to know about an
external module (for which you need to know the name and package path) with
class names (that you also need to know) -- especially given that the
general case, isinstance(x,y.__class__), is something one needs to use in
some circumstances in any case.

In the end,
(0).__class__ works -- it justs adds unfortunate "line noise" and
momentarily invokes the "is it an expression or is it a tuple" confusion

0 .__class__ works, too -- but is somewhat fragile because of the required
white space

Still, these are better than nothing.  :-)

Jim






More information about the Python-list mailing list