> Articles > Factory Function In Python

Factory Function In Python

A factory function in python is used to create function objects.

What is Factory Function?

We can have a function works as a factory which creates and returns function. We can return different functions based on parameter of function. As we have a function inside another function so closure is created and inner function will have access to factory function parameter even after it returns. This provides great flexibility for creation of functions. Let's see the implementation of python factory function.

Implementation

factoryfunction1.py

Python Factory Function Example 1 Source Code

Output

Executing Restart on Linux
Executing Shutdown on Windows

We can also have if statement outside and can create the function object based on value of parameter of factory function.

factoryfunction2.py

Python Factory Function Example 2 Source Code

Output

Executing Restart on Linux
Executing Shutdown on Windows


Suresh Kumar Srivastava is founder of online learning site coursegalaxy.com and author of popular books "C In Depth", "Data Structures Through C In Depth". He has 18+ years experience in industry and worked on architecture and design of multiple products. This article is from his course on Advanced Python.