Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add section on documentation and duck typing. #509

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 40 additions & 1 deletion docs/source/_get-started/making_connections.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
Connecting Nodes
================

Building a Connection
---------------------

..
**# TODO: Connect function and class based nodes**

Expand Down Expand Up @@ -41,4 +44,40 @@ With this, any attribute of any Node can be connected.

with zntrack.DiGraph() as graph:
generate_data = GenerateData(**kwargs)
process_data = ProcessData(data=generate_data.data)
process_data = ProcessData(data=generate_data.data)

Write documentation
-------------------
ZnTrack Nodes are designed to be flexible and easy to connect.
This is achieved through the concept of `duck typing <https://en.wikipedia.org/wiki/Duck_typing>`_, which allows Nodes to be connected as long as they have the correct attributes and methods.
To help document the required attributes and methods, we suggest using the ``typing.Protocol`` module.

For example, consider the Node ``ProcessData``, which expects an attribute ``data`` of type ``np.ndarray``.
We can define such a ``typing.Protocol`` as follows:

.. code-block:: python

import typing
import numpy as np

class HasData(typing.Protocol):
"""Protocol for Nodes with data attribute"""
data: np.ndarray

Then, we can use this ``HasData` protocol as a type hint for the ``input_data`` attribute of the ``ProcessData`` Node:
PythonFZ marked this conversation as resolved.
Show resolved Hide resolved

.. code-block:: python

from zntrack import Node, zn

class ProcessData(Node):
input_data: HasData | list[HasData] = zn.deps()

def run(self):
if not isinstance(self.input_data, list):
self.input_data = [self.input_data]

for data_node in self.input_data:
print(data_node.data.shape)

This highlights, that the ``ProcessData`` Node should work with any Node that has a ``data`` attribute of type ``np.ndarray``, whether it is a NumPy array generated by another Node from the same package, or generated by a Node from an entirely different library.