[TransWarp] Metaprogramming in Python
Dominikus Herzberg (EED)
Dominikus.Herzberg at eed.ericsson.se
Wed Jul 25 10:42:45 EDT 2001
Hi,
I'm doing some metaprogramming -- the code works fine but I still
don't precisely get how metaprogramming works internally. That
would also help me understanding TransWarp's code. The usual pattern
for defining a "MetaClass" is e.g.
class InterfaceMetaClass:
def __init__(self,name,bases,dict):
self.__name__ = name
self.__bases__ = bases
self.__dict = dict # We can't use __dict__ here!
The next step is instantiating this class object ...
InterfaceType = InterfaceMetaClass("InterfaceType",(),{})
... and to use this class instance as a base class within a class
definition. The idea is to regard the "base class" InterfaceType as
the type of the class object, e.g.
class Port(InterfaceType):
pass
The fun part is that
>>> type(Port)
results in
<type 'instance'>
Why? I understand that class definitions are an executable statement
in python. As soon as python passes the class definition Port, python
first evaluates the inheritance list, here InterfaceType, which should
evaluate to a class object. In this case, it evaluates to a class
instance instead! This is clearly the point of where the magic begins
... but how does it continue. Why does Port finally evaluate to a
class instance but having typical properties of a class object like
__dict__ or __bases__? What does Port make this sort of a hybrid
thing?
Comments are appreciated!
Thanks a lot,
Dominikus
More information about the PEAK
mailing list