pythongoogle-app-engineprotorpc

Python protoRPC: Recursive message class


I'm trying to make a message class for representing a tree , so naturally i went for:

class Node(messages.Message):
    name = messages.StringField(1)
    children = messages.MessageField(Node,2,repeated=True)

but this wouldn't work since at line 3 Node is not defined yet and is unresolved.

Any idea on how to make a tree (arbitrary tree ,not a tree of fixed depth) using protorpc messages ?


EDIT:

tried:

class AbstractNode(messages.Message):
    pass


class Node(AbstractNode):
    name = messages.StringField(1)
    children = messages.MessageField(AbstractNode, 2, repeated=True)

endpoints complains: MessageDefinitionError: Message types may only inherit from Message


Solution

  • You do this by using a string:

    >>> class Node(messages.Message):
    ...     name = messages.StringField(1)
    ...     children = messages.MessageField('Node',2,repeated=True)
    

    You can see an example of this in the echo service demo here:

    https://github.com/google/protorpc/blob/master/demos/echo/services.py#L81