Factory Functions: Supercharge your Python code

Ash Johnson
3 min readNov 5, 2022

If software design, object-oriented programming and code efficiency are things you think about when developing your applications or ETL scripts in Python, let me introduce you to one of my favourite design patterns — The Factory Function.

The Factory Function or Factory Pattern was one of the design patterns in “Design Patterns: Elements of Reusable Object-Oriented Software” by Eric Gamma, Richard Helm, Ralph Johnson and John Vlissides. The Factory Function helps us separate the creation of a function from its use.

Let us start by creating our connection API:

Connection API parent abstract class and subclasses

We first start by creating our parent class of APIConnector as an abstract base class with just one function for connect(). This function does not do anything and is there as an @abstractmethod.

We then create our two main classes for connection the TwitterAPI and FacebookAPI class which inherit from the APIConnector class. They both have a connect() function. For our example the functions just print a simple statement. However, in a real implementation these will actually contain the code required for connecting.

--

--

Ash Johnson
Ash Johnson

Responses (4)