I have a class and a normal constructor but I wish to preprocess the parameters and postprocess the result so I provide a mandated Factory constructor. Yes, I know that this is an unusual meaning for Factory and I also know that I could use memoization to do my processing but I had problems with extending a memoized class.
I wish to prevent myself from accidentally using the normal constructor and this is one way of doing it.
import inspect
class Foo():
def __init__(self):
actual_class_method = Foo.Factory
# [surely there's a way to do this without introspection?]
allowed_called_from = {name:method for name,method in inspect.getmembers(Foo, inspect.ismethod)}['Factory']
actual_called_from = inspect.currentframe().f_back.f_code # .co_name)
print("actual class method = ",actual_class_method," id = ",id(actual_class_method),",name = ",actual_class_method.__name__)
print("allowed called from = ",allowed_called_from,", id = ",id(allowed_called_from),", name =",allowed_called_from.__name__)
print()
print("actual called from = ",actual_called_from,", id = ",id(actual_called_from),", name =",actual_called_from.co_name)
@classmethod
def Factory(cls):
Foo()
Foo.Factory()
produces output
actual class method = <bound method Foo.Factory of <class '__main__.Foo'>> id = 3071817836 ,name = Factory
allowed called from = <bound method Foo.Factory of <class '__main__.Foo'>> , id = 3072138412 , name = Factory
actual called from = <code object Factory at 0xb7118f70, file "/home/david/Projects/Shapes/rebuild-v0/foo.py", line 15> , id = 3071381360 , name = Factory
Suppose I wished to check that the constructor to Foo() had been called from its Factory. I can find various things about the method whence Foo() was called such as its name and the filename where it was compiled, and this would be sufficient to stop me accidentally calling it directly, but I can't see a way of saying (the method that Foo() was called from) is (the method Factory() in the class Foo). Is there a way of doing this?