Skip to content

Instantly share code, notes, and snippets.

@DocGarbanzo
Last active January 30, 2022 21:36
Show Gist options
  • Save DocGarbanzo/09e5a5985be3bed840328ae5170a9ff6 to your computer and use it in GitHub Desktop.
Save DocGarbanzo/09e5a5985be3bed840328ae5170a9ff6 to your computer and use it in GitHub Desktop.
Python factory method - creating objects from dictionaries

Python factory method

This is a simple approach for a factory that makes objects out of dictionaries. The only two ingredients are

  • a metaclass Factory to manage the class registration and export a make function
  • a base class Creatable that implements the creation funtion by calling the initializer

The user only has to derive classes from the base class Creatable and then has access to a dictionary-based creation of instances of such classes.

Please note

In the file where Factory.make() is called, it is necessary to import the Creatable concrete class otherwise the metaclass initialisation will not run.

#!/usr/bin/env python3
"""
Simple factory implementation where we are using a metaclass to register
creation functions of classes derived from a base class Creatable.
"""
class Factory(type):
"""
Metaclass to hold the registration dictionary of the constructor functions
"""
register = {}
def __init__(cls, name, bases, d):
cls.register[cls.__name__] = cls.create
@classmethod
def make(mcs, concrete, kwargs):
return mcs.register[concrete](kwargs)
class Creatable(object, metaclass=Factory):
"""
Base class for factory creatable objects, implementing create()
"""
@classmethod
def create(cls, kwargs):
return cls(**kwargs)
if __name__ == '__main__':
# Here we are in user land where we create new classes derived from
# Creatable
class A(Creatable):
def __init__(self, number):
self.number = number
print('created A: number =', self.number)
class B(Creatable):
def __init__(self, word):
self.word = word
print('created B: word =', self.word)
# Now we can factory-create objects of our classes from lists of
# dictionaries
data = [{'A': {'number': 4}}, {'B': {'word': 'hello world!'}}]
for d in data:
for obj, ctor in d.items():
Factory.make(obj, ctor)
# The script will print the following lines:
# created A: number = 4
# created B: word = hello world!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment