I'm devloping a module that works with another module. The other module requires class attributes to be set before the __init__ method (let's work under the assumption that the behavior of this other module cannot be changed). These class attributes (Signal in the example below) are derived partially from an object that comes from my code.
The method shown below is a disaster for many reasons. For example,
my_obj1andmy_obj2are not guaranteed to exist; the import in the other module will fail in this case.- There could be a need to create 2 different instances of
OtherModuleVodoo1using 2 different instances from my code (my_obj).
This is a skeleton of the code to explain:
import Signal, Device
from my_module.setup import my_obj1, my_obj2
class OtherModuleVodoo1(Device):
# The class signal attributes must be defined before the __init__
# and rely upon an object from my module
x = Signal(my_obj1.cmds['thing_x'], 'thing_x')
y = Signal(my_obj1.cmds['thing_y'], 'thing_y')
# ...
# ...
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class OtherModuleVodoo2(Device):
x = Signal(my_obj2, 'thing1')
y = Signal(my_obj2, 'thing2')
# ...
# ...
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# now in my file I do this
dev1 = OtherModuleVodoo1()
dev2 = OtherModuleVodoo2()
# but would much prefer to do this
dev1 = OtherModuleVodoo(my_object_input = my_obj1)
# where I don't need ```Vodoo1, Vodoo2``` but can have a generic
solution.
Question:
Is there a way to "input" parameters to the construction of a class (not to the initialization of a class instance)?
What I tried and why each did not work.
- Metaclasses. These feel close to the right approach but I wasn't able to get it to work.
__new__but this doesn't populate the namespace within the class definition (before the__init__)- Setting
my_obj1 = Noneuntil anOtherModuleVodoo1instance is needed and then modifying the class attribute before instantiating an object:
An example of attempt 3:
xyq = None
class Test2():
print(xyq)
def __init__(self):
print(self.xyq)
Test2.xyq = 55
t2 = Test2()
However, here the output is:
None
55
I anticipate responses that focus completely on changing the approach. That is warranted. However, my immediate question is how to best band-aid what I have.