How to integrate your Python Class into Plotly Dash dashboards
By: Edoardo Romani
Tags: Python Class, Object Oriented, Python, Dash, Plotly

Code overview

Our simple application makes use of two Python scripts:

Payback_Calculator.py: the script in which you can define our own Payback Tracker class object and its functionality Payback_Application.py: the script in which you run and render the Plotly Dash application

Let’s now go over both scripts step by step, from class instantiation to app rendering.

1) Defining our custom class: the Payback Tracker

Class instantiation and attributes

Classes in Python are initialized with the class keyword, followed by the class name. The code below creates and names a Payback_Tracker class.

Upon instantiation, Python classes make use of the built in __init__() function to give a class its attributes. Attributes are class object properties you can attach to a given class instance, depending on its definition and use you plan to make of the class and its objects.

This Python Tracker class takes in 5 explicitly given attributes upon instantiation (name,initial_cost,usage_benefit,frequency,period) plus 3 others, described below:

name: the name of the class object instance (i.e. “bike”)

initial_cost: the cost of the item representing the upfront investment required

usage_benefit: the monetary value of the opportunity cost extracted by using the item

frequency: usage frequency of the item within a given period

outstanding_balance: The monetary value left to amortize with usage. Upon instantiation and thus at the time of the initial investment, it is equal to initial_cost

period: usage period reference (i.e. “daily”,”weekly”,”monthly”, or “yearly” usage)

The Tracker instance also initializes three additional attributes it will make use of to keep track of relevant object information as the item gets “used” and amortized by the owner:

balance_history: The collection of outstanding_balance values the tracker uses to keep track of the payback history of the item. Initialized as a list with the first outstanding_balance value as the initial value.

payback_counter_period: numerical count of the periods passed since usage started. Initialized as 0 at the time of initial investment.

usage_total: keeps count of the total monetary value equivalent of the item’s usage at any given time. (i.e. after buying the item and having it used 2 times with a usage_benefit of 4$, the usage_total value after one period would be 2*4$=8$)

Class methods

With class methods, you can put your class attributes to good use by enriching our Tracker with custom functionality and by thus defining its behavior via functions (the methods) typical of that class.

Our Payback_Tracker class has three methods:

get_result(): given an object’s initial_cost, usage_benefit, frequency and period, returns the estimated number of usages, or periods as defined in the period attributes.

Source: Author

generate_balance_history(): returns a list of amortized values in descending order (starting from the initial investment value of the item), which represent the value of the initial item left to payback. Decreases linearly with usage.

Source: Author

get_balance_history(): returns the list of amortized values as generated in the generate_balance_history() method

Source: Author

get_balance_data(): returns a data-frame format version of the balance_history of the item

The Payback_Tracker class now has its own attributes and methods, and given its inputs it can compute the amortization history and timeline of an item.

Let’s now put it all to work by embedding the object into our Plotly-Dash application!

2) Embedding the Payback Tracker class into the app’s functionality

The Payback Tracker app resides in Payback_Application.py. The script has three main sections described below.

Package import and Dash app creation

First, let’s import the necessary packages to be able to run our plotly-dash app (lines 1–11); then, our app’s instance can be initialized with the relevant dash and .server methods (lines 13–15).

Notice how the script also imports our Tracker class from Payback_Calculator.py, which enables access to definition of Payback_Tracker class instances and their methods (line 11).

2. App’s HTML layout (with some built-in CSS formatting)

Next, our HTML components can be defined as a list into the app.layout variable. You can also refer to the above image of the app’s front-end for reference.

The main components (embedded into a main container <div> element set at the beginning) are:

an H1 header setting the app’s title (“Item Payback Period Calculator”)

(“Item Payback Period Calculator”) a <div> element containing the description of the app, with title and subtitle

of the app, with title and subtitle an additional <div> with a header ( form legend ) and three paragraph <p> tags providing legend information around the user input fields.

) and three paragraph <p> tags providing legend information around the user input fields. another <div> containing input fields for the user to fill in with the variable the Payback_Tracker class will use to calculate the estimated time required to return from the investment: the item’s name, initial cost, usage benefit and frequency, as well as the relevant period. These elements are coded as Input elements in the dash app for the back-end to be able to refer to the user’s input and store those values as variables our class will make us of in the next step.

for the user to fill in with the variable the Payback_Tracker class will use to calculate the estimated time required to return from the investment: the item’s name, initial cost, usage benefit and frequency, as well as the relevant period. These elements are coded as elements in the dash app for the back-end to be able to refer to the user’s input and store those values as variables our class will make us of in the next step. the layout closes with <div> tag (id=’output_graph’) which will contain our data output graph, as well as a <div> tag (id=’output_text’) which will render the output from calling the get_result() class method on the user’s input variables

Having styled our page elements with some additional but essential in-line CSS, you can now move on to the app’s main functionality piece.

3. Calling our Payback_Tracker class to enable app’s functionality

Our app’s functionality in Dash is enabled by one and only one function, called generate_graph(). The app makes use of a Python decorator to define input and output components the function will make use of.

Our 5 input components are coming from the input elements defined as part of the layout in the prior section and referenced by their ID fields in HTML. They are passed in the generate_graph() function as arguments and correspond to our 5 key attributes of the Payback_Tracker class (name,initial_cost,usage_benefit,frequency,period).

There are also 2 Output elements defined, respectively the ’output_graph’ and ’output_text’ HTML elements, which will be used to return and render the function’s output.

The function’s body is then defined. After the user fills in the form with his/her 5 input elements, these are passed as input arguments to generate_graph(). The function then creates a Payback_Tracker class instance with those 5 attributes (line 11) called object_, and successively calls the generate_balance_history() and the get_balance_data() methods on those inputs, storing the result of the latter in a data variable (line 13).

Using such data, a bar chart (stored in the fig variable) is then created via the plotly.express (px) library (lines 15–18).

The function the returns both the fig variable, embedding it in the first of the 2 output elements (‘output_graph’) and then also embeds the result of calling the get_result() method into the ‘output_text’ element.

Therefore, whenever the user fills in the form, the 5 input fields are used by the class to:

create an instance of that class

call its methods on its attributes

use the generate_graph() function to capture the input, process the methods and render the results (the fig bar-chart plus the output of get_result()) into the Dash HTML layout, repeating this workflow every time the user modifies the input fields in the form.

In this way, you have been able to interact with Dash elements and processing them via your custom class, then also used to render visual output to the user via the generate_graph() function!

Our simple app’s functionality is now complete.

Summary, code repository, useful resources and next steps

I hope this simple example serves as a useful illustration of how to potentially make use of your own class objects to create data visualization elements with Dash!

Thanks for reading!

Code repo: https://github.com/edoard0/Item-Payback-Calculator

References: