mar10 / nutree

A Python library for tree data structures with an intuitive, yet powerful API.
https://nutree.readthedocs.io
MIT License
21 stars 3 forks source link

Make use of generics #8

Open Viicos opened 1 month ago

Viicos commented 1 month ago

Hi, thanks for this library. I'm experimenting with it to represent a tree like structure and seems to fit well.

I think it would be nice to make use of generics for the Node and Tree class, something like:

NodeT = TypeVar("NodeT", bound=Node)

class Tree(Generic[NodeT]):
    def __init__(
        self,
        name: str | None = None,
        *,
        factory: type[NodeT] | None = None,
        ...
    ) -> None: ...

    def add_child(self, child: NodeT | Tree | Any, ...) -> NodeT: ...

DataT = TypeVar("DataT")

class Node(Generic[DataT]):
    def __init__(
        self,
        data: DataT,
        *,
        parent: Node,
        data_id: DataIdType | None = None,
        node_id: int | None = None,
        meta: dict = None,
    ): ...

    @property
    def data(self) -> DataT: ...

    def set_data(self, data: DataT, *, data_id=None, with_clones: bool = None) -> None: ...

I think most of the time people will create trees with the same node class, and with the same data type as well. I can work on a PR if you think this is a good idea.

mar10 commented 1 month ago

Hi, that would be an improvement, we can experiment with it. Let's see where it takes us. We need have tests and support for the TypedTree as well. And also deal with Python version 3.8+ somehow, I think.