0

I was wondering if this approach for creating a singleton was correct.

my_class.py

class MyClass(object):
    def a_method(self):
        print("Hello World")
    ...

MY_CLASS_SINGLETON = MyClass()

another module:

from my_class import MY_CLASS_SINGLETON

if __name__ == "__main__":
    MY_CLASS_SINGLETON.a_method()

So this code is working for me, but my wonder is if the garbage collector could destroy the MY_CLASS_SINGLETON instance before it is used by any other module, as at the end it is just a temporary variable inside the my_class.py module.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Ricard Pérez del Campo
  • 2,387
  • 1
  • 19
  • 22
  • 3
    It's not a "temporary variable". It's a name defined in your module. Python also isn't going to garbage collect `MyClass`, even though that's also just a named object in your module. – deceze Jul 14 '16 at 07:32
  • Ok, I didn't know about the scope. And about the "singleton", it is true that I can create more instances, but in my case I don't worry about this. Thank you for the clarification though :) EDIT: part of this answer was not for you but for @AnnetteC, sorry for the confucion. – Ricard Pérez del Campo Jul 14 '16 at 08:04
  • Possible duplicate of [Is there a simple, elegant way to define singletons in Python?](http://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons-in-python) – pat Jul 14 '16 at 13:16

1 Answers1

0

I would assume that your implementation is not a save singleton as far as you can easily create new instances of MyClass. A singleton should avoid this by holding this instance by itself and just returning this instance - your instance is hold outside of the class. (But I am myself new to Python and a the moment I just maintain procedural written Python code.)

But did you have a look here?

Community
  • 1
  • 1
AnnetteC
  • 490
  • 2
  • 5
  • 20
  • Thank you for the link. I had already seen it, but I found it "too complicated" compared to what I had in mind (and for my needs, of course). And about being able to create multiple instances, this is ok for my case. Thank you. – Ricard Pérez del Campo Jul 14 '16 at 08:08
  • But what you are doing is not implementing the singleton pattern. You only provide a constant. Probably it is ok for your use case but if other rely on your code and believe that it is a singleton it can cause problems. Please, have a look on the ideas of the singleton pattern. – AnnetteC Jul 14 '16 at 13:07
  • You are right, I just used the wrong name 'singleton'. The only thing I wanted from the singleton pattern is to be able to access the same instance from anywhere. – Ricard Pérez del Campo Jul 14 '16 at 13:21