1

I have a instance of a class that I need in all my program (let assume there is no concurrency issue).

Is better to have something like this:

def main():
    usefulClass = usefulClass()
    self.a = A(usefulClass)
    self.b = B(usefulClass)

class A/B:
     def __init__(self, usefulClass):
         self.usefulClass = usefulClass

     def method(self):
         self.usefulClass.whatever()

if __name__ == "__main__":
    main()

or like this:

usefulClass = usefulClass()

def main():
    self.a = A()
    self.b = B()

class A/B:
     def __init__(self):
         pass

     def method(self):
         usefulClass.whatever()

if __name__ == "__main__":
    main()
rpadovani
  • 7,101
  • 2
  • 31
  • 50

2 Answers2

2

The first is better because it avoids using globals – global variables can cause tons of headaches later on.

For example, what if you accidentally modify usefulClass in some other module? It'd be very difficult to trace what's going wrong and why.

Community
  • 1
  • 1
Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94
2

It depends of the size of your code. In your little example, then the first solution is definitely better. Because global variables are basically hell.

However, imagine that the object you need only once is data from a configuration file, and hundreds of other objects may query it. You don't want to pass the config object to each and every object in your program, nor you want to parse hundreds of time the configuration. In those cases, the config is made into a Singleton.

Let's be honest, a Singleton is a global variable with a nice name. But it is a necessary evil if your program is too large − the first solution would cause more problems than it solves.

So, there is no absolute answer for this question, it's all about modelization, size and context.

T. Claverie
  • 11,380
  • 1
  • 17
  • 28