0

I see there are many examples how to create singleton objects with python.

Is there a simple, elegant way to define singletons?

I would like to use a singleton in a FastAPI script and I am worried that the singleton item might not be cleared from memory once my script is done.

What I see in this example for instance

def singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance

@singleton
class MyClass:
    ...

that the instance is managed within the decorator. How can I tell the decorator to free that memory piece when I finish all my logic? I had a similar issue before with Java long time ago and thinking here loud. All I would like to do is instances = {}

martineau
  • 119,623
  • 25
  • 170
  • 301
El Dude
  • 5,328
  • 11
  • 54
  • 101
  • 1
    Python isn't a language where memory is managed manually... it has automatic memory management. **Python exposes no way to free objects explicitly**. Why are you worried that "the singleton might not be cleared from memory once my script is done." What does that even mean? Once the process terminates, the OS would clean up the memory anyway, since you say you are running this as a script? – juanpa.arrivillaga Sep 13 '21 at 23:01
  • 2
    Also, this is a **terrible** decorator. Don't use this. Now `MyClass` **is not a class at all**. And to begin with, singleton classes really have very little practical use. What is it that you are gaining from this? Why not jsut create a module with an object in it? You don't have to expose a class, that is basically what you are doing here anyway. – juanpa.arrivillaga Sep 13 '21 at 23:02
  • So, if for some reason you feel you *must* use a singleton, then use the [metaclass approach](https://stackoverflow.com/a/33201/5014455) – juanpa.arrivillaga Sep 13 '21 at 23:11
  • Yes, agree to all points, I was thinking of using a variable from a module too. But somehow thought about singletons. To your question - it runs in FastAPI, so I am not sure if a background worker would consider a task completed if some item is still set in memory. Side note - it's possible (albeit difficult - add some C to the mix here, lol ) to create memory leaks with Python. So I want to prevent a memory leak or some interesting side behaviour. Thanks for the responses. The metaclass looks good too. – El Dude Sep 13 '21 at 23:30
  • If you created one as a class (possibly via subclassing or a metaclass) you could easily add a class method to it that explicitly cleared all instances. – martineau Sep 13 '21 at 23:33

0 Answers0