A question about Type Hints

Hi there,

Congrats on the new release of Plotly.py!

And I have a question, what should I fill in the ?? field below?

from typing import Union

def gen(children: Union[str, ??]) -> ??:
    return html.Div(children)

Thanks!

1 Like

I’m curious about this too as I’m not sure I have a totally satisfactory strategy to this. My current approach is to use the Component base class:

from dash import html
from dash.dependencies import Component

def gen(children: str | Component) -> Component:
    return html.Div(children)

(Note that I’m using the | operator available in Python 3.10 instead of Union)

But it goes a bit deeper than this. The children argument, in addition to str and Component, can also be “numeric”, None, or a list of these.

Which I think could look like this:

from typing import Union
from dash import html
from dash.dependencies import Component

def gen(children: None | str | float | Component | list[None | str | float | Component]) -> Component:
   return html.Div(children)

(Apparently float implicitly includes int)

But actually, we can be even more explicit. It turns out that values of the children prop in components don’t have to be a list, they can be list-like, which Dash defines as either a tuple or a MutableSequence.

Since this is all getting a bit convoluted, it might makes sense to use type aliases:

from collections.abc import MutableSequence
from dash.dependencies import Component

SingleChild = None | str | float | Component
ChildrenProp = SingleChild | MutableSequence[SingleChild] | tuple[SingleChild] 

def gen(children: ChildrenProp) -> Component:
    return html.Div(children)

I’ve only just thought about the nuances around the proper type annotation for the children prop in writing this reply, and I’m definitely not a Python typing expert, so this is my first stab at it. Would be keen to hear if anyone else has ideas here!

1 Like

hey @adamschroeder do you happen to know if there’s any resources on how to formally annotate the types of Dash components/children, or if this is something the Dash team has thought about?

Thanks for sharing! I’ve only used it when manipulating dictionaries and just learned that it can be used here!

1 Like

I know that NumPy provides an API numpy.typing to do this, haven’t seen any other library that does something similar.