nye17
nye17

Reputation: 13357

How to create a singleton class based on its input?

I have a class defined as

class Conditional_Singleton(object):
    def __init__(self, condition=None):
        self.initialization = some_func_of(condition)

Since the "initialization" step really takes a lot of time to run and the output could be huge, I would really like that the class not be recreated over and over again given the same input, but do so once the input changes. Any ideas?

Upvotes: 2

Views: 492

Answers (2)

agf
agf

Reputation: 176980

class Conditional_Singleton(object):
    saved_insances = {}
    def __new__(cls, condition = None):
        if not condition in cls.saved_instances:
            cls.saved_instances[condition] = super(
                Conditional_Singleton, cls).__new__(cls)
        return cls.saved_instances[condition]
    def __init__(self, condition = None):
        if not hasattr(self, 'initialization'):
            self.initialization = some_func_of(condition)
        

This will save the dict of created instances in the class itself and automatically reuse them if the same condition is passed.

Edit: Just saw your comment. You need to find a good way to hash condition for this to work, so unless it derives from a class that implements __hash__, you need to implement it yourself.

Edit 2: Using __new__ instead of __init__ for the singleton.

Upvotes: 5

g.d.d.c
g.d.d.c

Reputation: 48048

You could potentially do something like this:

myInstances = {}

myInstances['condition'] = Conditional_Singleton('condition')

In other parts of your code you'd do something like this:

if 'condition' in myInstances:
  # something down here that works with that instance

Whether or not that fits with your requirement is going to depend on whether or not you can simplify conditions to be something hashable for use as a dictionary key.

Upvotes: 1

Related Questions