Jean Robatto
Jean Robatto

Reputation: 1

Class memoization vs static class

just looking for opinions or thoughts about how you choose between using a static class vs a memoized class.

For example, consider these 2 python classes:

@cached
class A:

    def __init__(self):
        #expensive computation

    def a(self):
        #do something

this class would be called like:

A().a()

now consider this second class:

class B:

    is_init = False

    @classmethod
    def __init(cls):
        #expensive computation
        cls.is_init=True

    @classmethod
    def b(cls):
        if not cls.is_init: 
             cls.__init()
        #do stuff

called like:

B.b()

they both only do the expensive computation once - so, which one is the better approach? what are the tradeoffs?

not needed for this question:)

Upvotes: 0

Views: 167

Answers (1)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 96349

Here is the most basic approach I can think of, and it's a perfectly reasonable approach:

import functools

@functools.cache
def initialize_connection():
    # expensive initialization
    return connection

Then, you can just do:

def A:
    def __init__(self):
        self.connection = initialize_connection()
    def get(self):
        # use self.connection to do stuff
        return stuff

Another alternative, which is essentially equivalent:

class A:
    connection = initialize_connection()
    ...
    def get(self):
        # use self.connection to do stuff
        return stuff
    ...

The key issue isn't really whether you should make it a class variable or an instance variable, IMO, it's that you have a function that initializes your connection that is cached. Now you can utilize that function anywhere you might need a connection. When I said I would just use dependency injection, I mean I would have:

class A:
    def __init__(self, connection):
        self.connection = connection
    def get(self):
        # use self.connection to do stuff
        return stuff

a = A(initialize_connection())

Upvotes: 0

Related Questions