Metaclasses & docstrings in 2.2

Bengt Richter bokr at oz.net
Fri Jul 26 15:08:58 EDT 2002


On Wed, 24 Jul 2002 14:12:39 +0200, =?ISO-8859-1?Q?Walter_D=F6rwald?= <walter at livinglogic.de> wrote:
>Alex Martelli wrote:
>
>> [...]
>> ...would you please share your uses for metaclasses?  I can use
>> all the good examples I learn about -- it's hard to teach people
>> how to use metaclasses without actual motivation, and the more
>> real-life examples I can collect and quote, the more likely I
>> can help people achieve that motivation!
>
>The upcoming release of XIST (http://www.livinglogic.de/Python/xist/)
>has several uses of metaclasses (see
>http://www.livinglogic.de/viewcvs/index.cgi/LivingLogic/xist/_xist/xsc.py?rev=2.117.2.25&content-type=text/vnd.viewcvs-markup
>for the source code.
>
>The first example is a customized repr for nested classes,
>that shows the class nesting:
>
First, thank you for showing an example with __metaclass__ not bound to
a class defined outside. ISTM this way of doing things should be shown to
be an alternative to the __metaclass__ = MCxxx pattern of defining an outside
metaclass and binding to it. It would be a good addition to decrintro.html.

(Of course that brings up the question of whether there are pros and cons
associated with the two ways, other than being able to reuse the same metaclass).

There appears to have been a little glitch in cutting and pasting, but after
the change, it worked for me as advertised.

>class Base(object):
>     class __metaclass__(type):
>         def __new__(cls, name, bases, dict):
>             dict["__outerclass__"] = None
>             res = type.__new__(cls, name, bases, dict)
>             for (key, value) in dict.items():
>                 if isinstance(value, type):
>                     value.__outerclass__ = res
>             return res
>
>         def __repr__(self):
>             return "<class %s/%s at 0x%x>" % (self.__module__, 
>self.__fullname__(), id(self))
 ^--( line obviously wrapped )
>
>     def __fullname__(cls):
>         name = cls.__name__
---[ needs a dedent >-------------------
>             while 1:
>                 cls = cls.__outerclass__
>                 if cls is None:
>                    return name
>                 name = cls.__name__ + "." + name
---< needs a dedent ]-------------------
>     __fullname__ = classmethod(__fullname__)
>
[...]
Now I can play with this pattern. Thanks ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list