"my brain hurts" or is isinstance broken?

Jonathan Hogg jonathan at onegoodidea.com
Thu Jul 4 05:11:52 EDT 2002


On 4/7/2002 8:40, in article
eaef2e43.0207032340.6ccf12c3 at posting.google.com, "Robert Kuzelj"
<robert_kuzelj at yahoo.com> wrote:

> it is implicit cause i dont want to ask what kind of
> class that is but if it is an instance.

I also don't think of it as implicit. It's explicit, just the other way
around. If you divide the universe of objects into "class" or "instance",
then "not class" is as good as "instance".

> that is is is it an object
> created by an instantiation-action (aka x = X()) this is very
> clearly distinglishable im my code from creating a class-object
> (class X:...).

Unfortunately, whilst distinguishable in the code, the underlying mechanism
is indistinguishable. A class declaration like this:

>>> class foo( object ):
...     def hello( self ):
...         print 'Hello World'
... 
>>> foo      
<class '__main__.foo'>
>>> f = foo()
>>> f
<__main__.foo object at 0x40a810>
>>> f.hello()
Hello World
>>> 

is actually executed as the (mostly) equivalent code:

>>> def hello( self ):
...     print 'Hello World'
... 
>>> foo = type( 'foo', (object,),
...             {'hello':hello, '__module__':__name__} )
>>> foo
<class '__main__.foo'>
>>> f = foo()
>>> f
<__main__.foo object at 0x40a5d0>
>>> f.hello()
Hello World
>>> 

That is why you can't determine if an object is a class or not without
checking to see if its type is 'type' (or 'ClassType'). A class *is* an
instance - not just theoretically, but in the concrete "a constructor was
called to make this thing" kind of way.

If you want to work on Python's typing system you'll have to get your head
around this.

Jonathan




More information about the Python-list mailing list