trouble with the C API

Bernhard Herzog herzog at online.de
Mon Aug 21 18:09:20 EDT 2000


Stefan Seefeld <seefelds at magellan.umontreal.ca> writes:

> How is the type of an object determined if not by inspection of the
> supported protocols (i.e. the existence of certain attributes, methods etc.) ?
> 
> Well, looking at the (C) sources I get part of the answer: Each object
> has a type object associated with it.

Yes. The type is a C-struct that contains C-function pointers that
implement the various methods (In some cases there's an extra level of
indirection and the type contains a pointer to a struct of functions).

These functions are C-functions that implement getattr, setattr, str,
repr, getitem, etc. The pointers may be NULL, indicating that the method
is not implemented.

> Let's rephrase the question then:
> 
> doesn't each object have two types, one static type, determined by the
> type object it refers to and one dynamic type, given through the presence
> (at a given point in time !) of a particular method or attribute ?

Strictly speaking, each object has only one type. This is the type
returned by the builtin type function. Instances also have a class which
can also be considered a type but that's a bit different. An instance's
type is InstanceType.

The special methods such as __getitem__ are only relevant for class
instances. For instance f(arg) will call f.__call__ if d is a class
instance but it will call the C-function of the type(f) that implements
the call operation. An instance can indeed change what protocols it
supports over time, so it has sort of two types as you describe, but a
C-object can't (at least not in the same way because what methods it has
is irrelevant[1]).

To make this even more complicated, the instance type object implements
some of these C-functions in such a way that they call the appropriate
__*__ method, so the interpreter can and does treat instances like the
other objects but in some cases but it special cases instance objects
nonetheless and calls their special methods directly. __getitem__ is one
of the cases where the interpreter always goes through the C-function.


  Bernhard

[1] Except for the file protocol which doesn't have a C-level
equivalent.

-- 
Bernhard Herzog   | Sketch, a drawing program for Unix
herzog at online.de  | http://sketch.sourceforge.net/



More information about the Python-list mailing list