Cool design pattern for typed APi's with stored Variant

Cool design pattern for typed APi’s with stored Variant.

Hi, just would like to share an cool design pattern,
i think i unconsciously learned this workflow from the PythonObject/TypedPythonObject,
that Connor pushed to repo a while back :smiley:

Anyway, it is sort of an Split->Rejoin idea,
and it is most useful for user,
because the user don’t need to worry about checking Variant.

comptime Nestables = Variant[LayoutStack, Text, TextureWidget, Spacing]

@fieldwise_init
struct NestableWrapper(Copyable, Movable):
    "Type used for storing Nestables in an list."
    var val: ArcPointer[Nestables]

struct TypedNestableWrapper[T: SpaceUsable]():
    "Type used for returning an Nestable in an Typed way to user."
    var val: ArcPointer[Nestables]

    def __getitem__(mut self) -> ref[origin_of(self.val)] Self.T:
        #debug asset that isa[T]()
        return self.val[][Self.T]

def main():
    var n = api.create_node(LayoutStack(...)) 
    #Api stored the node in an tree or an list.
    #var n is still typed LayoutStack for user.

So for my api, i have this cool overload:

    def append[NewT: SpaceUsable](
        mut self, 
        var arg: NewT, out ret: TypedNestableWrapper[NewT]
    ) where _type_is_eq_parse_time[Self.T, LayoutStack]():
        comptime assert _type_is_eq[LayoutStack, Self.T]()
        ret = self.val[][LayoutStack](arg^) #Appended to layout on the way.

A similar pattern in the context of compilers: xYang.mojo/.cursor/rules/mojo-variant-pattern.mdc at main · exergy-connect/xYang.mojo · GitHub

May be worth collecting these as skills that AI coding agents can apply, ideally as part of the official Mojo skills.

This reminds me of the “Gang of Four” book on design patterns: