[Python-Dev] metaclass insanity

Walter Dörwald walter@livinglogic.de
Tue, 05 Nov 2002 11:21:14 +0100

Martin v. Loewis wrote:
> Guido van Rossum <guido@python.org> writes:
>>In the case of nested classes, a possible solution might be for
>>X.Y.__name__ to be "X.Y" rather than plain "Y".  Then a simple change
>>to pickle (or to getattr :-) could allow the correct unpickling.
> I'd rather expect that X.Y.__module__ is "Foo.X".

Even better would to have "X.Y.__outerclass__ is X",
i.e. __outerclass__ as a (weak) reference to the class
in which X.Y was defined. What I came up with is this:

class nestedtype(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 __fullname__(cls):
       name = cls.__name__
       while 1:
          cls = cls.__outerclass__
          if cls is None:
             return name
          name = cls.__name__ + "." + name

    def __repr__(cls):
       return "<class %s/%s at 0x%x>" % \
          (cls.__module__, cls.__fullname__(), id(cls))

    Walter Dörwald