Defining circular references using zope.schema

给你一囗甜甜゛ 提交于 2019-12-06 04:07:14

Modify the field after definition:

#imports elided

class IFoo(Interface):
    bar = schema.Object(schema=Interface)

class IBar(Interface):
    foo = schema.Object(schema=IFoo)

IFoo['bar'].schema = IBar

Martijn's answer seems a bit more graceful and self-documenting, but this is a bit more succinct. Neither is perfect (compared to say, Django's solution of using string names for foreign keys) -- pick your poison.

IMHO, it would be nice to specify a dotted name to an interface instead of an identifier. You could pretty easily create a subclass of schema.Object to this end for your own use, should you find that approach useful.

You could define a base, or abstract, interface for IUser:

class IAbstractUser(Interface):
    name = schema.TextLine(title=u"User's name")

class IGroup(Interface):
    name = schema.TextLine(title=u"Group's name")
    user_list = schema.List(
        title=u"List of Users in this group", 
        value_type=schema.Object(IAbstractUser))

class IUser(IAbstractUser):
    group_list = schema.List(
        title=u"List of Groups containing that user",
        value_type=schema.Object(IGroup))

Because IUser is a subclass of IAbstractUser, objects implementing the former also satisfy the latter interface.

Edit: You can always still apply sdupton's dynamic after-the-fact alteration of the IGroup interface after you defined IUser:

IGroup['user_list'].value_type.schema = IUser

I'd still use the Abstract interface pattern to facilitate better code documentation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!