Reputation: 283
I am writing a class to extract data from some files and write it to a postgres database. Now, the problem is that for each instance, I am pulling some info from database which is constant for all other instances.
So what I would like to do is just run a function / piece of code once my first object is created and this function (or code) will extract that info from the database. Then I want that my other instances can access this info instead of contantly querying the database again and again as this info is constant. I was thinking in direction of class variables, decorators. I was going through pytest where they have fixtures with scope (@pytest.fixture(scope = 'module')) where we can put the code which needs to be run once and later other functions that we are testing can use that info.
Can somebody please help how this can be achieved?
Upvotes: 7
Views: 6767
Reputation: 5011
You can use a class attribute for this and check if it is already set in the constructor of you class:
class MyClass(object):
postgres_data = None
def __init__(self):
if not MyClass.postgres_data:
MyClass.postgres_data = self.fetch_data()
def fetch_data(self):
pass
Upvotes: 7