This module provides a simple way to prevent the direct creation of an instance of a class. Instead a classmethod
of this class can be used.
You can install this python module via pip:
pip install simple-factory-pattern
Otherwise the module can be downloaded from PyPI: https://pypi.org/project/simple-factory-pattern/
-
Import the module:
from simple_factory_pattern import FactoryPatternMeta
-
Create a class that uses the above meta class:
class NewClass(metaclass=FactoryPatternMeta): pass
-
Add a
classmethod
to the new class that returns an instance of the class:@classmethod def create_instance(cls): return NewClass()
You can choose any name for the method. But it must be a
classmethod
!It's also possible to define multiple
classmethod
s. Only in those methods a new instance of the class can be created.
It's not possible to create an instance of the class directly:
instance = NewClass() # this will fail
This throws a FactoryException
(also included in the simple_factory_pattern
package).
The only way to get an instance is to call the above definded classmethod
:
instance = NewClass.create_instance() # this works