Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a function only once in a Class - Python

Tags:

oop

python-3.x

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?

like image 829
ArkanSaaS Avatar asked Dec 18 '18 10:12

ArkanSaaS


People also ask

How do I run a function only once in Python?

run_once.pydef run_once(f): """Runs a function (successfully) only once.

How do you call a function only in Python?

Summary. To use functions in Python, you write the function name (or the variable that points to the function object) followed by parentheses (to call the function). If that function accepts arguments (as most functions do), then you'll pass the arguments inside the parentheses as you call the function.

How do you split a function in Python?

The Python split() method divides a string into a list. Values in the resultant list are separated based on a separator character. The separator is a whitespace by default. Common separators include white space and commas.

What does a Python function return by default?

That default return value will always be None . If you don't supply an explicit return statement with an explicit return value, then Python will supply an implicit return statement using None as a return value.


1 Answers

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
like image 118
kalehmann Avatar answered Oct 04 '22 04:10

kalehmann