Trusted answers to developer questions

Why and how to use a data model in Python

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

Introduction

There are many options for temporary in-memory storage of data in Python including dictionaries and arrays. However, there are some advantages to defining a class that acts as a data model.

Let’s use the example of a Python program written for a Pizza place. Since pizza can come in different sizes, with all sorts of toppings and many other options, the program needs a good data structure to keep all those organized.

widget

Data model class

The example below may be a little silly, but it gets the point across. Since the code is an example, we are skipping a lot of other variables that the class would store.

In real code, size might be an enum.

# data.py
class Data(object):
_number_of_slices = int()
_size = str() # real code might use an enum
_price_in_cents = int()
# real code would define a lot more class variables
def set_number_of_slices(self, num):
self._number_of_slices = num
def get_number_of_slices(self):
return self._number_of_slices
def set_size(self, size):
self._size = size
def get_size(self):
return self.size
. . .

Example

Creating a class that can store and expose data makes writing code easier. It makes your code clean and clear to the reader. In the example below, the program prompts for the size of the pizza, stores that size, and then retrieves the size to confirm.

# main.py
from data import Data
d = Data() # create an instance of the Data class
print('What size pizza would you like? ') # prompt
s = input() # wait for input
d.set_size(s) # store input in data model
print(f'To confirm, you asked for a {d.get_size} pizza')

Application

Classes (data models) that “do nothing” but function to store data in memory and get the data when requested can be a pleasure to use when coding.

These are especially useful when there are a large number of data points that could be processed by a function.

# ugly function without using data model
def calculate_cost_of_goods(cost_of_dough, cost_of_sauce, cost_of_oil, cost_of ....)
# ugly function using a dictionary
# when I use dictionaries, I can NEVER remember the key values
# that makes coding with dicts a pain
def calculate_cost_of_goods(cost_dict):
return cost_dict["cost_of_dough"] + cost_dict["cost_of_sauce"]
# clean function using data model
# where the model class name is cost_of_goods
# accessing members of the class cost_of_goods is
# simple due to IDE completion of dot notation
def calculate_cost_of_goods(cost_of_goods):
return cost_of_goods.dough + cost_of_goods.sauce ..

Add extra value to the data model

Our pizza program could be enhanced to get user input for a large number of variables. At the end of the prompting section, we want to display all of the choices the user made back to them so they can visually confirm their order.

We can take advantage of the string built-in class method.

data.py
class Data(object):
_number_of_slices = int()
. . .
def _str_(self):
print(f'Size: {self.get_size()}')
print(f'Slices: {self.get_number_of_slices()}')
print(f'Toppings: {self._get_toppings()}')

By adding that string method, we can make the pizza program more user friendly like this:

#main.py
from data import Data
d = Data() # create an instance of the Data class
print('What size pizza would you like? ') # prompt
s = input() # wait for input
d.set_size(s) # store input in data model
print('How many slices? ')
sl = input()
d.set_number_of_slices(sl)
print('What toppings') . . .
print('Here is a summary of your order')
print(d)
# the above print(d) will call the _str_ method
# in the Data class
#
# The result would look something like...

> Size: Medium

> Slices: 10

>Toppings: pepperoni, mushrooms

Code notes

  1. I chose to use underscores in the class variable names to indicate that they are “private” variables.

  2. If you are wondering what that lower case f in the print statements is all about, stay tuned for another shot on that topic.

RELATED TAGS

python
data structures
classes
model
Did you find this helpful?