I have issues trying to implement an easy to use abstract factory.
To be able to define concrete factories this way:
class MyConcreteFactory( ... ):
@classmethod
def __load(cls, key):
obj = ... # Loading instructions here
return obj
To be able to use concrete factories this way
obj = MyConcreteFactory[key]
I tried to define a metaclass for factories which override bracket operator and encapsulate the factory pattern:
class __FactoryMeta(type):
__ressources = {}
@classmethod
def __getitem__(cls, key):
if key not in cls.__ressources:
cls.__ressources[key] = cls.__load(key)
return cls.__ressources[key]
@classmethod
def __load(cls, key):
raise NotImplementedError
class ConcreteFactory(metaclass=__FactoryMeta):
@classmethod
def __load(cls, key):
return "toto"
a = ConcreteFactory["mykey"]
print(a)
This failed because the __load method called is the one from the metaclass and not the one from the concrete class. The result is:
Traceback (most recent call last):
File "C:\Users\walter\workspace\Game\src\core\factories.py", line 34, in <module>
a = ConcreteFactory["mykey"]
File "C:\Users\walter\workspace\Game\src\core\factories.py", line 19, in __getitem__
cls.__ressources[key] = cls.__load(key)
File "C:\Users\walter\workspace\Game\src\core\factories.py", line 24, in __load
raise NotImplementedError
NotImplementedError
I tried to remove the __load method from the meta class but then I got this (predictable) error:
Traceback (most recent call last):
File "C:\Users\walter\workspace\Game\src\core\factories.py", line 30, in <module>
a = ConcreteFactory["mykey"]
File "C:\Users\walter\workspace\Game\src\core\factories.py", line 19, in __getitem__
cls.__ressources[key] = cls.__load(key)
AttributeError: type object '__FactoryMeta' has no attribute '_FactoryMeta__load'
Is there a way to access class method from a metaclass? Am I wrong and should do this in an other way? Then which way?
class __FactoryMeta(type):
ressources = {}
def __getitem__(cls, key):
if key not in cls.ressources:
cls.ressources[key] = cls.load(key)
return cls.ressources[key]
def load(cls, key):
raise NotImplementedError
class ConcreteFactory(metaclass=__FactoryMeta):
@classmethod
def load(cls, key):
return "toto"
a = ConcreteFactory["mykey"]
print(a)
You should not use @classmethod
in the metaclass. An instance of the metaclass is the class itself so:
def __getitem__(cls, key):
is actually the class and:
@classmethod
def __getitem__(metacls, key):
gets the metaclass as first argument.
Eiher case, I believe metaclasses make this problem much more complicated. I believe a more viable approach would be to create a base factory class, subclass it accordingly, and use the subclass'es instance as the factory.