If I have a function that returns a plotly express figure, what is the correct way of type hinting?
The figure is of type:
<class 'plotly.graph_objs._figure.Figure'>.
Should I type hint by separately importing plotly, and writing:
-> plotly.graph_objs._figure.Figure
?
import pandas as pd
import plotly.express as px
import plotly
long_df = px.data.medals_long()
fig = px.bar(long_df, x="nation", y="count", color="medal", title="Long-Form Input")
print (type (fig))
def plot_bar (df: pd.DataFrame) -> plotly.graph_objs._figure.Figure :
fig = px.bar(long_df, x="nation", y="count", color="medal", title="Long-Form Input")
return fig
plot_bar(long_df)
It's a matter of convention, but usually when people work with plotly graph_objects
, they have the following import:
import plotly.graph_objects as go
This means you can replace plotly.graph_objs._figure.Figure
with go.Figure
so your type hinting is a little easier to read:
def plot_bar(df: pd.DataFrame) -> go.Figure():
fig = px.bar(long_df, x="nation", y="count", color="medal", title="Long-Form Input")
return fig