Skip to content

Recursive types

Latest
Compare
Choose a tag to compare
@amoffat amoffat released this 11 Sep 03:29
6c1a4e2

0.6.0 Adds support for recursive types, meaning types can refer to themselves, or other types, in a recursive nature, and it all just works:

from dataclasses import dataclass
from rich.pretty import pprint
from manifest import ai

@dataclass
class Character:
    name: str
    occupation: str
    social_graph: "SocialGraph"

@dataclass
class SocialGraph:
    friends: list[Character]
    enemies: list[Character]

@ai
def get_character_social_graph(character_name: str) -> SocialGraph:
    """For a given fictional character, return their social graph, resolving
    each friend and enemy's social graph recursively."""

graph = get_character_social_graph("Walter White")
pprint(graph)
SocialGraph(
    friends=[
        Character(
            name='Jesse Pinkman',
            occupation='Meth Manufacturer',
            social_graph=SocialGraph(
                friends=[Character(name='Walter White', occupation='Chemistry Teacher', social_graph=SocialGraph(friends=[], enemies=[]))],
                enemies=[Character(name='Hank Schrader', occupation='DEA Agent', social_graph=SocialGraph(friends=[], enemies=[]))]
            )
        ),
        Character(
            name='Saul Goodman',
            occupation='Lawyer',
            social_graph=SocialGraph(friends=[Character(name='Walter White', occupation='Chemistry Teacher', social_graph=SocialGraph(friends=[], enemies=[]))], enemies=[])
        )
    ],
    enemies=[
        Character(
            name='Hank Schrader',
            occupation='DEA Agent',
            social_graph=SocialGraph(
                friends=[Character(name='Marie Schrader', occupation='Radiologic Technologist', social_graph=SocialGraph(friends=[], enemies=[]))],
                enemies=[Character(name='Walter White', occupation='Meth Manufacturer', social_graph=SocialGraph(friends=[], enemies=[]))]
            )
        ),
        Character(
            name='Gus Fring',
            occupation='Businessman',
            social_graph=SocialGraph(
                friends=[Character(name='Mike Ehrmantraut', occupation='Fixer', social_graph=SocialGraph(friends=[], enemies=[]))],
                enemies=[Character(name='Walter White', occupation='Meth Manufacturer', social_graph=SocialGraph(friends=[], enemies=[]))]
            )
        )
    ]
)