I have an interesting problem. I would like to write a class, which when inherited provides to all children classes the following behavior:
- sets its self.id attribute to a UUID value -- if this is the first time class got instantiated, a new UUID is generated -- the UUID value is reused for the same class, when it is instantiated many times
Now, the fun part: I want the mechanism above to work, regardless of the path used to instantiate this class. Let's assume the following:
from .Package.Class1 import Class1
from TopPackage.Package.Class1 import Class1
from .Package.Class2 import Class2
from TopPackage.Package.Class2 import Class2
In both situations, I would like Class1 to generate the same self.id value in both import styles. I would also like Class2 to generate a different self.id value from Class1, but the same between its own import styles.
So far, I wrote the following code for a class classes 1 and 2 would inherit from:
class ClassWithId(ABC):
_EXISTING_OBJECT_IDS = dict()
def __init__(self):
if self in ClassWithId._EXISTING_OBJECT_IDS.keys():
self.id = ClassWithId._EXISTING_OBJECT_IDS[self]
else:
self.id = uuid.uuid4()
ClassWithId[self] = self.id
However, I have a few problems in here:
- ClassWithId must inherit from class ABC because it is also an interface for classes 1 and 2
- trying to put self as key in dict() results in TypeError: 'ABCMeta' object does not support item assignment
- I am generally unsure, if this approach is going to be resistant to different import styles, because from Python's perspective class type .Package.Class1.Class1 and TopPackage.Package.Class1.Class1 are 2 different objects
Any ideas?
UPDATE: I have integrated Elrond's suggestion into my code, and but different import levels (package-wise) yield different UUID values for the same class:
<class 'StageTwo.Steps.SsTestHandler1.SsTestHandler1'> 3583c89c-5ba8-4b28-a909-31cc27628370
<class 'tests.TestStages.StageTwo.Steps.SsTestHandler1.SsTestHandler1'> f4ead4a0-f5f7-4d95-8252-0de47104cb2f
<class 'StageTwo.Steps.SsTestHandler2.SsTestHandler2'> 8bd9a774-0110-4eee-a30c-a4263ad546cf
<class 'tests.TestStages.StageTwo.Steps.SsTestHandler2.SsTestHandler2'> 773d84c4-82a3-4684-92b5-51509e6db545
Maybe I forgot to mention, but my ClassWithId is inherited by ClassX and ClassY down the line, and it is these 2 classes, which are expected to be resistant to the situation I have shown above (being imported with different path, yet still retaining the same UUID).