Deferred Evaluation in Recursive Expressions?

Peter Otten __peter__ at
Wed May 10 07:53:09 CEST 2006

birchb at wrote:

> That's a good fix. But I have misgivngs about needing a global name
> registry. I need to support anonymous types and types with local
> (lexical) scope. For example:
> def makeAnonymousRecursiveType(T):
>     # anonymous type expression with local scope
>     LinkedList = (T, lambda: LinkedList)
>     return LinkedList
> local = makeAnonymousRecursiveType(int)

class Names(object):
    def __getattribute__(self, name):
        return name

types = Names()

class Type(type):
    all = {}
    def __new__(mcl, name, bases, dict):
        assert "_typedef" not in dict
        dict["_typedef"] = dict.pop("typedef", ())
        cls = type.__new__(mcl, name, bases, dict)
        cls.all[name] = cls
        return cls
    def get_typedef(cls):
        def get(item):
            result = cls.all.get(item)
            if result is None:
                result = type(cls).all.get(item, item)
            return result
        return tuple(get(item) for item in cls._typedef)
    def set_typedef(cls, value):
        cls._typedef = value
    typedef = property(get_typedef, set_typedef)

class TypeDef:
    __metaclass__ = Type

class LinkedListA(TypeDef):
    typedef = (int, types.LinkedListB)

class LinkedListB(TypeDef):
    typedef = (int, types.LinkedListA)

print LinkedListA.typedef
print LinkedListB.typedef
print LinkedListA.typedef

def LocalTypeDef():
    class LocalTypeDef(TypeDef):
        all = {}
    return LocalTypeDef

def makeAnonymousRecursiveType(T):
    class LinkedList(LocalTypeDef()):
        typedef = (T, types.LinkedList)
    return LinkedList

print makeAnonymousRecursiveType(int).typedef
print makeAnonymousRecursiveType(str).typedef

Go with lambda, I'd say...


More information about the Python-list mailing list