Python Design Patterns

Factory Method Pattern in Python

Let a factory decide which class to create, so the calling code only works with a common interface.

  • Advanced
  • 2 min read
  • 1 runnable example
What you'll learn
  • Separating creation from use
  • A factory method that returns different classes
  • Adding a new type without changing callers
create_notification(kind)
  • Notificationsend(message)
    • EmailNotification"email"
    • SmsNotification"sms"
The caller only sees Notification.send().

Ask for an interface, get the right class

The problem

When code creates objects with their concrete class names everywhere (EmailNotification(), SmsNotification()), adding a new channel means finding and editing every place. A factory keeps the choice of class in one spot.

Think of it like this

A factory method is like a vending machine. You press "email" or "sms" and get a ready product; you do not need to know which shelf it came from. Adding a new product means stocking the machine, not changing how customers press buttons.

From a vending machine to code
create_notification("email")🔘 Press the email button
factories🗄️ The machine's shelves: name to class
factories[channel]()📦 Build the right product
notification.send("Hello")📨 Use it the same way whatever it is
Callers ask for a kind of object; the factory picks the class.
In one sentence

The Factory Method pattern moves object creation into one function or method that decides which concrete class to build, so callers depend only on the shared interface.

Key points

  1. EmailNotification and SmsNotification both offer the same method, send.
  2. factories maps each channel name to its class.
  3. factories[channel]() looks up the class and creates an object of it.
  4. The caller only uses notification.send(...) and never names a concrete class.

When should you use it?

  • Choosing a class from configuration or user input, such as a notification channel or file format.
  • Hiding complicated construction behind one call.
  • Adding new variants without touching the code that uses them.

When not to use it

  • Only one class exists and is unlikely to change: calling it directly is clearer.
  • Construction needs many optional parts: the Builder pattern fits better.

Example code

Run code →
main.py
class EmailNotification:
    # Factory Method: creation is separated from object usage.
    def send(self, message):
        return f"Email: {message}"


class SmsNotification:
    def send(self, message):
        return f"SMS: {message}"


def create_notification(channel):
    # Centralize the concrete-class selection.
    factories = {"email": EmailNotification, "sms": SmsNotification}
    return factories[channel]()


notification = create_notification("email")
print(notification.send("Hello"))
Get a Run button for this example

Result of running the code

Email: Hello

Code explanation

Both notification classes have a send method, so code that uses them does not care which one it receives. create_notification keeps the mapping from channel names to classes in one dictionary and creates the chosen class with factories[channel](). The caller asks for "email", gets an EmailNotification and simply calls send("Hello").

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Replace the sample domain while preserving the pattern structure.
  2. Compare the pattern with a simpler implementation and explain the tradeoff.
  3. Write tests for each participant before adding another implementation.
Run in the Python compiler →

Common mistakes

Not handling an unknown channel

factories[channel] raises KeyError for an unsupported name.

Problem
return factories[channel]()
Fix
if channel not in factories:
    raise ValueError(f"Unknown channel: {channel}")
return factories[channel]()

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges