[Python-Dev] metaclass insanity

Guido van Rossum guido@python.org
Tue, 05 Nov 2002 12:05:21 -0500

> 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))

I kind of like __fullname__ as a useful attribute (though I'd make it
an attribute or property [== computed attribute] rather than a
method).  But if setting the __name__ of an inner class to
"Outer.Inner" doesn't break too much existing code, I'd prefer that --
no new attributes needed.

I don't see any use for __outerclass__ *except* for computing the full
name.  And there are better ways to do that if you have help from the

--Guido van Rossum (home page: http://www.python.org/~guido/)