How can 'type' be an instance of itself?
Terry Reedy
tjreedy at udel.edu
Fri May 29 02:07:27 EDT 2009
LittleGrasshopper wrote:
> On May 28, 4:37 pm, Christian Heimes <li... at cheimes.de> wrote:
>> LittleGrasshopper wrote:
>>> This is probably trivial, but it's driving me mad somehow. All (new
>>> style) classes are instances of 'type' by default, unless a custom
>>> metaclass is specified. I take this to mean that when a class
type(ob) simply looks up ob.__class__. For built-in classes, that is
all it means.
>>> declaration is found in the code, an instance of 'type' representing
>>> that class is created by calling type.__init__. What really gets me is
>>> how can 'type' be an instance of itself. In order to create 'type' we
>>> would need to call type.__init__, but it seems at this point it
>>> wouldn't exist. Probably a dumb question, which I hope someone can
>>> explain in some detail.
Actually, it is type.__new__ that creates the new object (as is true of
all classes). .__init__, when present, initializes mutable objects
already created by .__new__.
This is a perceptive, not a dumb question.
>> The classes 'type' and 'object' are written in C. You can do things in C
>> code that aren't possible from pure Python code. The circular
>> dependencies between 'type' and 'object' are created during the boot
>> strapping phase of the interpreter.
In other words, the interpreter is god with respect to built-in objects.
For instance, the interpreter has to mutate 'immutable' objects in
order to give then their immutable (thereafter) values. So setting
type.__class__ to type itself is no more of a big deal than the above,
or setting any builtin.__class__ to type.
>>>>> type(type)
>> <type 'type'>
>>>>> type.__bases__
>> (<type 'object'>,)
>>>>> object.__bases__
>> ()
>>>>> type(object)
>> <type 'type'>
>>
>> Christian
>
> And just to clarify that I do really understand what this means, I
> gather that what it entails is that 'type' is an instance of itself
> just from a conceptual point of view.
In regard to their creation, yes. But thereafter, isinstance(type,
type) is as concretely True as for anything.
tjr
> In other words, the code for the
> (meta)class 'type' is created statically by object code (compiled C
> code) before the python runtime is initiated (you referred to it as
> the interpreter bootstrapping phase.) I also guess that this code sets
> __class__ and __metaclass__ to the 'type' object itself (I am guessing
> a self-referencial pointer in C.) While I just am hypothesizing on the
> details, please let me know if you sense that I have misunderstood any
> essential part of your explanation.
>
> Thanks,
>
> Lukas
More information about the Python-list
mailing list