7

I have an underlying class which I want to place in some code. I only want it to be instantiated or started once for a given app although it might be called many times.. The problem with the code below is that LowClass is started over and over again. I only want it to start once per test..

import logging

class LowClass:

    active = False

    def __init__(self):
        self.log = logging.getLogger()
        self.log.debug("Init %s" % self.__class__.__name__)
        if self.active:
            return
        else:
            self.active = True
        self.log.debug("Now active!")

class A:
    def __init__(self):
        self.log = logging.getLogger()
        self.log.debug("Init %s" % self.__class__.__name__)
        self.lowclass = LowClass()

class B:
    def __init__(self):
        self.log = logging.getLogger()
        self.log.debug("Init %s" % self.__class__.__name__)
        self.lowclass = LowClass()

class C:
    def __init__(self):
        self.log = logging.getLogger()
        self.log.debug("Init %s" % self.__class__.__name__)
        self.a = A()
        self.b = B()


class ATests(unittest.TestCase):
    def setUp(self):
        pass

    def testOne(self):
        a = A()
        b = B()

    def testTwo(self):
        c = C()

Thanks for pointing out my problem!!

Jed Smith
  • 15,584
  • 8
  • 52
  • 59
rh0dium
  • 6,811
  • 4
  • 46
  • 79
  • 2
    With the proper name in hand -- "singleton" -- there's now a number of questions discussing this topic on SO (like Alex Martelli's Borg pattern, et alii). Vote for close now that asker has appropriate term for the design pattern. – Jed Smith Oct 15 '09 at 23:52

5 Answers5

9

See singleton in python.

Ewan Todd
  • 7,315
  • 26
  • 33
3

What you need is to implement the Singleton Design pattern in python

I've found this implementation I hope it helps

OscarRyz
  • 196,001
  • 113
  • 385
  • 569
2

When you import a module in python, it is natural singleton. For example, in util.py, you have:

   class MyClass(object):
        ......

    g_my_obj = MyClass()

in a.py, you import g_my_obj:

from util import g_my_obj

in b.py, you import g_my_obj again:

from util import g_my_obj

Safely, there is only one g_my_obj created no matter how many times you import it.

Yarkee
  • 9,086
  • 5
  • 28
  • 29
2

Look up "singleton pattern". It looks like Python you are dealing with, so you might have to search a bit harder. I now there are plenty of examples in C++.

EToreo
  • 2,936
  • 4
  • 30
  • 36
1

I believe that the problem with the code shown is that you set self.active=True. This will create an attribute for the instance and set that to True, whereas I believe that you want to set the active of the class itself to True. So, instead of self.active=True, try self.__class__.active=True.

Nikwin
  • 6,576
  • 4
  • 35
  • 43