I want to share data across different instances of a class, but the data must be provided externally the first time the class is created.
I have written the snippet below.
class Foo(object):
_config = False
eggs = None
def __init__(self, spam, eggs=None):
if Foo._config:
# Assume initialized and eggs exists
print(Foo.eggs)
else:
if eggs is None:
raise ValueError('eggs must be provided the first time')
else:
Foo.eggs = eggs
Foo._config = True
print("Scrambled {}?".format(Foo.eggs))
self.spam = spam
print("Class variable - eggs: {}".format(Foo.eggs))
print("Instance variable - spam: {}".format(self.spam))
which seems to work ...
>>>Foo._config
False
>>>a = Foo('chicken', 'eggs')
Scrambled eggs?
Class variable - eggs: eggs
Instance variable - spam: chicken
>>>Foo._config
True
and the second time doesn't raise an error and shares the class variable
>>>b = Foo('duck')
eggs
Class variable - eggs: eggs
Instance variable - spam: duck
My question is whether this is a good approach? I have seen this question which suggests that including things in __init__
that are only called once is a bad idea, and I should use a metaclass?
My justification is that eggs will actually contain a very large pandas dataframe that I don't to repeat with each instance.