Template Method — Python Design Patterns — SS Blog

Study Section
2 min readMar 7, 2022


Template Method — Python Design Patterns — SS Blog
Template Method — Python Design Patterns — SS Blog

The Template method is a Behavioral Design Pattern that outlines the operation’s skeleton while leaving the specifics to the child class to develop. Its subclasses can override the method implementations as needed, but the invocation must follow the abstract class’s rules. It is one of the most straightforward behavioral design patterns to comprehend and use. Such approaches are often utilized in framework development since they allow us to reuse a single piece of code by making little modifications. This also helps to reduce code duplication.

Problems without using Template Method

Suppose you are working on a data analysis application as a software engineer and using data mining techniques to process the data. Initially, your application was good with the JSON version of the data. But later your application needs to collect and process the other type of data too such as CSV, XML, PDF, etc. After developing the whole application for the other required formats you found that your application has lots of similar code. Like where you process and analyze the data. This is the point where you use template methods to tackle this problem.

Solution using Template Method

We can easily solve this problem by using the template method. The template method suggests breaking down the code into small methods/functions and calling these functions inside the template function.
Let’s understand this with an example:
def read_pdf():
# write the code to read pdf here
return "return pdf data"
def read_xml():
# write the code to read xml here
return "return xml data"
def read_csv():
# write the code to read csv here
return "return pdf data"
def read_json():
# write the code to read json here
return "return json data"
def process_data(data):
# write the code to process data
return "processed data"
def save_data(data):
# write code to save the data
def template_function(data):
print("`{}` was processed".format(data))
if __name__ == "__main__":

StudySection has a long list of certification exams that it offers through its online platform. The PHP Certification Exam is one of the programming certifications that it provides. Whether you are new to PHP programming or you have extensive experience in PHP programming, you can get a certification according to your level. Attach a PHP certification with your resume to get the most out of job offers.

Originally published at https://studysection.com on March 7, 2022.



Study Section

The most loved online platform for eCertification in several subjects including but not limited to Software Development, Aptitude and more.