What is the best way of implementing singleton in Python
Asked Answered
P

42

1683

This question is not for the discussion of whether or not the singleton design pattern is desirable, is an anti-pattern, or for any religious wars, but to discuss how this pattern is best implemented in Python in such a way that is most pythonic. In this instance I define 'most pythonic' to mean that it follows the 'principle of least astonishment'.

I have multiple classes which would become singletons (my use-case is for a logger, but this is not important). I do not wish to clutter several classes with added gumph when I can simply inherit or decorate.

Best methods:


Method 1: A decorator

def singleton(class_):
    instances = {}
    def getinstance(*args, **kwargs):
        if class_ not in instances:
            instances[class_] = class_(*args, **kwargs)
        return instances[class_]
    return getinstance

@singleton
class MyClass(BaseClass):
    pass

Pros

  • Decorators are additive in a way that is often more intuitive than multiple inheritance.

Cons

  • While objects created using MyClass() would be true singleton objects, MyClass itself is a function, not a class, so you cannot call class methods from it. Also for

    x = MyClass();
    y = MyClass();
    t = type(n)();
    

then x == y but x != t && y != t


Method 2: A base class

class Singleton(object):
    _instance = None
    def __new__(class_, *args, **kwargs):
        if not isinstance(class_._instance, class_):
            class_._instance = object.__new__(class_, *args, **kwargs)
        return class_._instance

class MyClass(Singleton, BaseClass):
    pass

Pros

  • It's a true class

Cons

  • Multiple inheritance - eugh! __new__ could be overwritten during inheritance from a second base class? One has to think more than is necessary.

Method 3: A metaclass

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

#Python2
class MyClass(BaseClass):
    __metaclass__ = Singleton

#Python3
class MyClass(BaseClass, metaclass=Singleton):
    pass

Pros

  • It's a true class
  • Auto-magically covers inheritance
  • Uses __metaclass__ for its proper purpose (and made me aware of it)

Cons

  • Are there any?

Method 4: decorator returning a class with the same name

def singleton(class_):
    class class_w(class_):
        _instance = None
        def __new__(class_, *args, **kwargs):
            if class_w._instance is None:
                class_w._instance = super(class_w,
                                    class_).__new__(class_,
                                                    *args,
                                                    **kwargs)
                class_w._instance._sealed = False
            return class_w._instance
        def __init__(self, *args, **kwargs):
            if self._sealed:
                return
            super(class_w, self).__init__(*args, **kwargs)
            self._sealed = True
    class_w.__name__ = class_.__name__
    return class_w

@singleton
class MyClass(BaseClass):
    pass

Pros

  • It's a true class
  • Auto-magically covers inheritance

Cons

  • Is there not an overhead for creating each new class? Here we are creating two classes for each class we wish to make a singleton. While this is fine in my case, I worry that this might not scale. Of course there is a matter of debate as to whether it aught to be too easy to scale this pattern...
  • What is the point of the _sealed attribute
  • Can't call methods of the same name on base classes using super() because they will recurse. This means you can't customize __new__ and can't subclass a class that needs you to call up to __init__.

Method 5: a module

a module file singleton.py

Pros

  • Simple is better than complex

Cons

  • Not lazily instantiated
Pap answered 20/7, 2011 at 10:47 Comment(37)
Another three techniques: use a module instead (often - generally, I think - this is a more appropriate pattern for Python but it depends a bit on what you're doing with it); make a single instance and deal with it instead (foo.x or if you insist Foo.x instead of Foo().x); use class attributes and static/class methods (Foo.x).Dianthe
@ChrisMorgan: If you're going to use class/static methods only, then don't bother making a class, really.Bonucci
Duplicate of stackoverflow.com/questions/42558/… and stackoverflow.com/questions/31875/….Vexillum
@Cat: yep. The third case would tend to be better expressed as the first or second.Dianthe
@Cat: The effect is similar, however the reasons behind creating a global variable can be just about anything, including not knowing any better. Why does one create a singleton? If you have to ask you shouldn't be here. This explicitness is not only more pythonic, but makes maintenance a lot more simple. Yes singletons are syntactic sugar for globals, but then classes are syntactic sugar for a whole bunch of unsightly stuff and I don't think anyone will tell you you're always better off without them.Pap
Maybe it would help if I were to explain the purpose. I wish to have a few different logging classes that work in different ways with a variety of different sources/destinations. Now I want to apply these loggers to a variety of different functions as a decorator, and only need one logger of each type, init'd against many different functions. I.e. One that appends to a text file, one prints stdout, one prints stderr, and another sets a trace for pdb. These would all then be triggered differently at different logging levels. To me logging has always seemed a natural candidate for Singletons.No?Pap
@Cat Anyway, whether or not Singletons are a good idea was never supposed to be the question. The question was supposed to be how they are best implemented. I'd guess my question will not be reopened, which is a shame. Anyhow, I wouldn't have described you as rude - I think a lively debate is always interesting, it's just rather not the point of stackoverflow.Pap
@BiggAl You copied the wrong code from my post. That's my fixes to Method #2, not my metaclass. I saw you want to run __init__ every time; I added that code to my post. I also commented on Method #4. Summary: it's bad for a class to be its own base class.Vexillum
@Vexillum Cheers for the edit, as I couldn't see the problem, as the method I had put up was a tweak of yours. To be honest, other than s/object/type/g, I don't see the problem - in yours a dict is shared with all Singleton type classes yes? And the __new__ method selects the correct one by using the class as its hash, creating it if not already done. In my version each class had access to only its own instance, or the base instance if that had been created, and then the __new__ method checks that it is an instance of the correct class. This surely shares less state ergo so is more desirable?Pap
@BiggAl The other problem is __call__ vs. __new__. In a metaclass, __new__ means when the class is new, not when the instance is new. You want the method called every time someone tries to make a new instance so you need to use __call__. Even if you fix your version to use type and super instead of object, it won't make singletons unless you use __call__ -- test it. _instance vs. _instances wasn't the problem. Your way might even be better, I have to think about it.Vexillum
Ah cool, I hadn't noticed that. Metaclasses seem very powerful, do you know of any resources that would show a little more about them? I found this question, but do you know of any other great resources?Pap
Check out the other SO questions that come up for "Metaclass Python". Read all of docs.python.org/reference/datamodel.html. Recently I saw bitshaq.com/2011/07/14/basic-intro-to-python-meta-programming which looks pretty good. Read secure.wikimedia.org/wikipedia/en/wiki/Metaclass. Just keep thinking "it's a class who's instances are class definitions".Vexillum
The anti-signletons sentiment is cargo cult programming at its worst. Same with people hearing (few bothered to actually read) "Goto statement considered harmful" and think gotos are a sign of bad code regardless of context.Wilds
Why can't i say that a class with only class methods and class attributes is a singleton class ?Pneumonia
@Pneumonia because strictly speaking that's a static class, or as close as you'd get in python. You can still add instance attributes unless you prevent instantiation, at which point it becomes more truly staticPap
@Pap but in python you can always use setattr(object,name,value) to add instance variable, i don't see any concrete reason of why should use any of those methods explained below to implement singleton, when python itself by default supports it. Let me know if i am missing anything.Pneumonia
With a Singleton you have only a single instance, ergo you can setattr without any inconsistencies. This is why I was saying that for a static class you would have to prevent instantiationPap
@Vexillum I need to make singleton on the basis of arguments instead of class names. I've posted a question here on SO -> stackoverflow.com/questions/39033946/…Orbicular
Hi, thanks for your elaborate post. I am fairly new to pattern programming and to python actually, and I am surprised that although method 2 seems to most well known one (it s everywhere), hardly ever someone mentions that despite only one object is created, init__() is called every time Singleton() or MyClass() are used anywhere. I didn't try, but AFAIK this is true for all other methods too. This hardly seems desirable when implementing a singleton, or am i missing something? Of course the solution consists of setting an attribute to avoid performing __init twice. Just curiousOrgell
@Orgell indeed you probably want some form of guard around init, although I'd also say that you very rarely want a Singleton, over the years since this question was written, I've only really needed a Singleton twice, and one of those was taken out when I made things more functional, and therefore this shared state became undesirablePap
How would you kill the object of the 3rd method?Fearful
@LiorMagen You wouldn't - how would you know that it wasn't going to instantiated again?Pap
@Pap I wouldn't, this will be relevant if I want to delete an existing object and create a new one instead of it. No way of doing that?Fearful
How about implementing it as a module?Squinteyed
Method 3 solved my problem with threading: class MyClass(threading.Thread, metaclass=Singleton):Infallible
@hejazzman further, the metaclass method negates the reason singletons are considered bad. For testing, you can take away the singleton-ness of the object so you no longer have shared state.Chromolithograph
@Chromolithograph I'm not sure this is the only reason singletons are sometimes considered an antipattern, but you're right that it does allow you to negate that particular issue. In a lot of cases the issue is not the fact that you use a singleton, but that ending up with an architecture where a singleton is useful often points to other architectural issues. Obviously this is a rule of thumb rather than anything hard and fast, which is why I'd still support the usefulness of my question all these years later ;)Pap
Saw (following). Yet, another way of implementing singleton pattern - apart from the answers to this post. Hope it helps! tutorialspoint.com/python_design_patterns/…Moffat
Are there any drawbacks of implementing the singleton class as a regular class and then just telling the users that it is not much useful to create multiple instances of it? As in the spirit of "we are all consenting adults here".Precritical
@Precritical only in so far as without enforcement it's easy to make mistakes, which can then often be difficult to debugPap
HEY!!!!!MAJOR CONS FOR METACLASS IMPLEMENTATION!!! If you do class MoreSingleton(Singleton,metaclass=OtherMeta) it will say TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its basesColitis
how does Method 3 usage code actually looks like? How do I access a method from it from elsewhere? I get Parameter 'self' unfilledFestus
Check this out for Singleton by args and kwargs. https://mcmap.net/q/18442/-how-to-create-singleton-class-with-arguments-in-pythonConnors
In Method 1, why MyClass becomes a function despite the fact that getinstance returns a class?Andriette
Thread safe implementation of method #3 (metaclass) here: https://mcmap.net/q/18443/-why-is-this-singleton-implementation-quot-not-thread-safe-quotRozanna
I would like to point out a small problem with the metaclass implementation mentioned in the question. The _instances mentioned in the class, isnt the one getting filled everytime a __call__ is made. cls._instances creates an _instances variable under the new class you made, and since there is only one instance, there will only every be one element in that for every class. Ideally it should have been Singleton._instances, which holds a map of all classes to their respective singleton instances. Doing it in the former way created problems during inheritance, but latter didnt.Nazario
@LiorMagen Regarding deleting the instance, you could implement a member function delete_instance function on the metaclass, which will become a class method for the proper class, which can now be used to delete the instance.Nazario
H
20

You just need a decorator, depending on the python version:


Python 3.2+

Implementation

from functools import lru_cache

@lru_cache(maxsize=None)
class CustomClass(object):

    def __init__(self, arg):
        print(f"CustomClass initialised with {arg}")
        self.arg = arg

Usage

c1 = CustomClass("foo")
c2 = CustomClass("foo")
c3 = CustomClass("bar")

print(c1 == c2)
print(c1 == c3)

Output

>>> CustomClass initialised with foo
>>> CustomClass initialised with bar
>>> True
>>> False

Notice how foo got printed only once


Python 3.9+

Implementation:

from functools import cache

@cache
class CustomClass(object):
    ...
Hekking answered 7/10, 2022 at 14:31 Comment(4)
The object won't be garbage collected in this case and you have to clear the cache (somewhere/sometime) if the class shouldn't life for the applications lifetime and is clearly a downside over the, already for this task, intended __new__ method.Mooned
@Mooned isn't the whole point of a singleton to stay in memory? If you garbage collect it, you effectively need to re-instantiate it if you need it again, which is the exact opposite of the goal here.Hekking
The term singleton describes that there is only one instance of it. Consider a larger application that uses the pattern in a "branch" and you keep accidentally a huge class in memory. I don't say your solution is a "no no" but it should be mentioned somewhere.Mooned
Also CustomClass is of type functools._lru_cache_wrapper, so you completely lose type information of the original class and isinstance(obj, CustomClass) doesn't work either.Dunston
V
1127

Use a Metaclass

I would recommend Method #2, but you're better off using a metaclass than a base class. Here is a sample implementation:

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]
        
class Logger(object):
    __metaclass__ = Singleton

Or in Python3

class Logger(metaclass=Singleton):
    pass

If you want to run __init__ every time the class is called, add

        else:
            cls._instances[cls].__init__(*args, **kwargs)

to the if statement in Singleton.__call__.

A few words about metaclasses. A metaclass is the class of a class; that is, a class is an instance of its metaclass. You find the metaclass of an object in Python with type(obj). Normal new-style classes are of type type. Logger in the code above will be of type class 'your_module.Singleton', just as the (only) instance of Logger will be of type class 'your_module.Logger'. When you call logger with Logger(), Python first asks the metaclass of Logger, Singleton, what to do, allowing instance creation to be pre-empted. This process is the same as Python asking a class what to do by calling __getattr__ when you reference one of its attributes by doing myclass.attribute.

A metaclass essentially decides what the definition of a class means and how to implement that definition. See for example http://code.activestate.com/recipes/498149/, which essentially recreates C-style structs in Python using metaclasses. The thread What are some (concrete) use-cases for metaclasses? also provides some examples, they generally seem to be related to declarative programming, especially as used in ORMs.

In this situation, if you use your Method #2, and a subclass defines a __new__ method, it will be executed every time you call SubClassOfSingleton() -- because it is responsible for calling the method that returns the stored instance. With a metaclass, it will only be called once, when the only instance is created. You want to customize what it means to call the class, which is decided by its type.

In general, it makes sense to use a metaclass to implement a singleton. A singleton is special because is created only once, and a metaclass is the way you customize the creation of a class. Using a metaclass gives you more control in case you need to customize the singleton class definitions in other ways.

Your singletons won't need multiple inheritance (because the metaclass is not a base class), but for subclasses of the created class that use multiple inheritance, you need to make sure the singleton class is the first / leftmost one with a metaclass that redefines __call__ This is very unlikely to be an issue. The instance dict is not in the instance's namespace so it won't accidentally overwrite it.

You will also hear that the singleton pattern violates the "Single Responsibility Principle" -- each class should do only one thing. That way you don't have to worry about messing up one thing the code does if you need to change another, because they are separate and encapsulated. The metaclass implementation passes this test. The metaclass is responsible for enforcing the pattern and the created class and subclasses need not be aware that they are singletons. Method #1 fails this test, as you noted with "MyClass itself is a a function, not a class, so you cannot call class methods from it."

Python 2 and 3 Compatible Version

Writing something that works in both Python2 and 3 requires using a slightly more complicated scheme. Since metaclasses are usually subclasses of type type, it's possible to use one to dynamically create an intermediary base class at run time with it as its metaclass and then use that as the baseclass of the public Singleton base class. It's harder to explain than to do, as illustrated next:

# works in Python 2 & 3
class _Singleton(type):
    """ A metaclass that creates a Singleton base class when called. """
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class Singleton(_Singleton('SingletonMeta', (object,), {})): pass

class Logger(Singleton):
    pass

An ironic aspect of this approach is that it's using subclassing to implement a metaclass. One possible advantage is that, unlike with a pure metaclass, isinstance(inst, Singleton) will return True.

Corrections

On another topic, you've probably already noticed this, but the base class implementation in your original post is wrong. _instances needs to be referenced on the class, you need to use super() or you're recursing, and __new__ is actually a static method that you have to pass the class to, not a class method, as the actual class hasn't been created yet when it is called. All of these things will be true for a metaclass implementation as well.

class Singleton(object):
  _instances = {}
  def __new__(class_, *args, **kwargs):
    if class_ not in class_._instances:
        class_._instances[class_] = super(Singleton, class_).__new__(class_, *args, **kwargs)
    return class_._instances[class_]

class MyClass(Singleton):
  pass

c = MyClass()

Decorator Returning A Class

I originally was writing a comment but it was too long, so I'll add this here. Method #4 is better than the other decorator version, but it's more code than needed for a singleton, and it's not as clear what it does.

The main problems stem from the class being its own base class. First, isn't it weird to have a class be a subclass of a nearly identical class with the same name that exists only in its __class__ attribute? This also means that you can't define any methods that call the method of the same name on their base class with super() because they will recurse. This means your class can't customize __new__, and can't derive from any classes that need __init__ called on them.

When to use the singleton pattern

Your use case is one of the better examples of wanting to use a singleton. You say in one of the comments "To me logging has always seemed a natural candidate for Singletons." You're absolutely right.

When people say singletons are bad, the most common reason is they are implicit shared state. While with global variables and top-level module imports are explicit shared state, other objects that are passed around are generally instantiated. This is a good point, with two exceptions.

The first, and one that gets mentioned in various places, is when the singletons are constant. Use of global constants, especially enums, is widely accepted, and considered sane because no matter what, none of the users can mess them up for any other user. This is equally true for a constant singleton.

The second exception, which get mentioned less, is the opposite -- when the singleton is only a data sink, not a data source (directly or indirectly). This is why loggers feel like a "natural" use for singletons. As the various users are not changing the loggers in ways other users will care about, there is not really shared state. This negates the primary argument against the singleton pattern, and makes them a reasonable choice because of their ease of use for the task.

Here is a quote from http://googletesting.blogspot.com/2008/08/root-cause-of-singletons.html:

Now, there is one kind of Singleton which is OK. That is a singleton where all of the reachable objects are immutable. If all objects are immutable than Singleton has no global state, as everything is constant. But it is so easy to turn this kind of singleton into mutable one, it is very slippery slope. Therefore, I am against these Singletons too, not because they are bad, but because it is very easy for them to go bad. (As a side note Java enumeration are just these kind of singletons. As long as you don't put state into your enumeration you are OK, so please don't.)

The other kind of Singletons, which are semi-acceptable are those which don't effect the execution of your code, They have no "side effects". Logging is perfect example. It is loaded with Singletons and global state. It is acceptable (as in it will not hurt you) because your application does not behave any different whether or not a given logger is enabled. The information here flows one way: From your application into the logger. Even thought loggers are global state since no information flows from loggers into your application, loggers are acceptable. You should still inject your logger if you want your test to assert that something is getting logged, but in general Loggers are not harmful despite being full of state.

Vexillum answered 23/7, 2011 at 3:28 Comment(31)
Look at googletesting.blogspot.com/2008/08/…. It is generally anti-singleton (for good reason) but it has a good explaination of why immutable singletons and singletons without side effects don't have the same problems, if you're careful. I'm going to quote it a bit at the end of my post.Vexillum
My problem with singletons is the stupid premise of "only one instance". That and tonne of thread safety problems. And dependency hiding. Globals are bad, and singletons are just globals with more problems.Bonucci
@BiggAl - You've mis-copied my code into your post -- that's my corrections to #2 not my metaclass. Also, you missed an important problem with that particular implementation of a decorator returning a class.Vexillum
@Cat There are very good uses for singletons. Lazy instantiation of hardware modules (especially in single threaded applications) is one of them (but thread safe singletons also exist).Tamatave
@Cat Another use came to mind (this is an example from the game I'm writing atm). I have an EventManager class written in C++ and exposed to Python. I need both languages to queue events in the same manager. I could, somehow, pass the same instance of the manager as a parameter to functions in both languages, but that would require a lot of work and the benefits would literally be nil. Actually, it might make the code harder to follow...Tamatave
@agf, when implementing Singleton through metaclass, why did you use "call" not "new"? and What's the difference?Embarrassment
@Embarrassment __new__ in a metaclass is when the class is new -- when it's defined, not when the instance would be new. Calling the class (MyClass()) is the operation you want to override, not the definition of the class. If you really want to understand how Python works, the best thing you can do (other than keep using it) is read docs.python.org/reference/datamodel.html. A good reference on metaclasses is eli.thegreenplace.net/2011/08/14/python-metaclasses-by-example. A good article on singletons is the series from the google blog I linked in this answer.Vexillum
Also, see stackoverflow.com/questions/31875/… for more singleton stuff if you haven't found that yet.Vexillum
@martineau It's an easy mistake to make. Python 3 has improved the metaclass syntax by making it a keyword argument: Logger(metaclass = Singleton).Vexillum
Instead of class Singleton(_Singleton('SingletonMeta', (object,), {})): pass you could remove one class by using an assignment: Singleton = _Singleton('Singleton', (object,), {}).Schaaff
@agf: May I ask you to elaborate on what you think is the right way to instantiate the internal state of the Logger class when using the metaclass Singleton? In particular, I find myself waffling on whether it is better to implement Logger.__init__ in order to lazily instantiate Logger's state, or to initialize Logger's state as a class member (not lazy, but more clear).Marcellus
Is it better to use Singletone._instances rather than cls._instances in the __call__ function? Otherwise the classes of Singletone may define its own class variable _instances and conflict with Singletone's.Debauch
@Debauch If you're worried about that, then the right thing to do would be to use __instances. See the name mangling docs for more info. That will prevent it being accidentally overridden without depending on the name of the class.Vexillum
@Christophe, consider also inheritance. Perhaps an App singleton, and lots of different types of Apps that inherent from that (LinuxApp, MobileApp, DesktopApp) etcIllfated
@Vexillum you mentined that _instances needs to be called on the cls level, and said it is not defined in the cls namespace. How is that possible? on which namespace does the cls._instances attribute defined?Adz
@Vinny I'm not totally sure I understand your question, feel free to clarify. In my example, what I'm saying is you can't accidentally do self._instances and override it in an instance of e.g. Logger. You'd have to do Logger._instances or type(self)._instances` or similar. So if other classes in multiple inheritance also use the name _instances, you're still generally going to be save from accidentally overriding it. Also as I mentioned in a comment, if you double the underscore Python will further hide the variable and make it even safer.Vexillum
Also, @Vinny -- was this post linked from a blog post of something? It seems like it's been getting a lot of votes recently; before that I'd totally forgot about it.Vexillum
@Vexillum I got it now, after some expirement. My doubt was where the _instances variable is actually saved (namespace), and I understand what you mean in your comment. I got to this by another answer of yours where you linked to this thread for further explanation. It is defiantly worth to be mentioned in a blogpost :-)Adz
@MichaelBerdyshev It should in Python 3.Vexillum
How about using a Singleton class in order to manage hardware components? Imagine, you have LCD display (on your RPi for example) and you wrote a small python script called displayManager.py. I think it completely fits into the "the most common reason is they are implicit shared state" definition mention here. If many other components are using this LCD display, they are using a shared state somehow. Why not doing so via a Singleton class.Sherrisherrie
Additional question: should one use weakref.WeakValueDictionary for _instances so that the instances get automagically removed when they are not used anymore? Imagine a "singleton" for DLL wrappers, where instances can be distinguished by path to DLL.Twedy
I think you can get the same effect by defining a base class BaseSingleton(metaclass=Singleton) and then using Logger(BaseSingleton). One possible advantage is everything I need defined with BaseSingleton, rather than having both a base class and a metaclass. Does this make sense?Histology
HEY!!!!!MAJOR CONS FOR METACLASS IMPLEMENTATION!!! If you do class MoreSingleton(Singleton,metaclass=OtherMeta) it will say TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its basesColitis
@Vexillum - Can you please update answer to include type hints? Having trouble as the type of anything that inherits from Singleton is not a generic. How can this be achieved?Amato
@Vexillum if you're still listening, why is _instances a dict rather than a variable that changes from None to the instance?Methoxychlor
@MikeC Because this way you can have multiple different singleton subclasses, each with a single instance, instead of just one instance for all subclasses.Vexillum
Correct me if wrong: this might be problematic if you deal with very large codebases, since the above Singleton implementation will populate its internal _instances state without ever removing references, which perhaps weakref would solutionPunk
@Punk it shouldn't ever remove references, because then it wouldn't be a singleton -- you'd get back a different instance the next time. The whole point is to keep the reference around forever. You could easily add a way to purge an instance if you wanted.Vexillum
I am thinking, as you explicitly mentioned 'data source', that a data source that exists only for data retrieval, that does not provide interface for any setter (only getter). Is this type of data source, ok for a singleton? Although there's information flowing into the application, the instance itself doesn't really have any mutable state, or mutation doesn't generate 'side-effect'. Thanks a lot.Pace
@Pace Yes, I'd agree that's a valid use-case -- though I would likely use a much simpler solution than this one, like CAt Plus Plus's below, if I were to do it today.Vexillum
@MikeC I did some tests and the subclass of a class that is an instance of a metaclass is also an instance of this metaclass (even without explicitly declaring the subclass with metaclass=MetaClass). So I believe that _instances could be _instance because the subclass will obtain this (unique) class variable from the metaclass.Byler
B
148
class Foo(object):
     pass

some_global_variable = Foo()

Modules are imported only once, everything else is overthinking. Don't use singletons and try not to use globals.

Bonucci answered 20/7, 2011 at 10:52 Comment(14)
why did you say "Don't use singletons"? Any reason?Embarrassment
This won't work if the singleton has to be pickled. Using the example you gave: s = some_global_variable; str = pickle.dumps(s); s1 = pickle.loads(str); print s is s1; # FalseMendelevium
@dividebyzero: the is operator tests for pointer equality. I would be rather surprised---to the point of calling it a bug---if pickle.loads returned a reference to a pre-existing object rather than a reference to a newly created one. Thus, testing whether s is s1 doesn't tell you anything about the suitability of using modules as singletons.Hinkley
@JonasKölker pickle.loads() does do that already, e.g. for instances of bool and NoneType. pickle.loads(pickle.dumps(False)) is False yields TrueAphaeresis
@leo-the-manic: fair point; however, that's just a side effect of Python interning the objects True, False and None, and has nothing to do with the code behind pickle.loads. Also, it's safe to do only for read-only objects. If pickle.loads were to return a reference to an already existing modifiable object—such as a module—that would be a bug. (And so I'm standing by my implication that dividebyzero's code example doesn't prove anything.)Hinkley
@Cat Plus Plus I think this will significantly increase the import time of the module. It is always better lazy create the object, when required.Pneumonia
This only works if all the imports happen the same way. import project.module and import .module will run the code twice.Materialism
If some_global_variable is used in some_module.py and that was the module under test, would mocking some_global_variable be possible?Pedro
should Foo be __Foo so that users won't casually just use that?Silures
This should have been the accepted answer given the specifics of this question. Notably, this is exactly the way the actual Python standard library implements the logging module. See the code: github.com/python/cpython/blob/master/Lib/logging/__init__.py. And it's still configurable, which seems to be why the original asker didn't want globals initialized at module import time.Isoelectronic
This is a very ambiguous answer, may I suggest re-editing it completely in light of the discussion.Marxismleninism
I imported the module in several different script files (all of which would use the "singleton"), with import ABC as X, and it was actually imported once for every script that had the import statement for the "singleton" module. So the variable I defined had its value reassigned each time the module was imported. I also tried removing the alias, and even importing it in every file of the project, same results. I'm on Python 3.9.6. Singleton with metaclass (from agf's answer) did the trick fantastically for my use case (logging, with a variable that must be initialized at compile time once)Oxidation
This is also problematic when the instantiation takes time (e.g. connecting to a DB). This will slow the whole program execution at import time.Willson
"try not to use globals" and then you go on using a global. Also you're totally missing the point of having a singleton per init kwargs or some other predicate which makes a singleton actually a viable solutionRoderich
M
93

Use a module. It is imported only once. Define some global variables in it - they will be singleton's 'attributes'. Add some functions - the singleton's 'methods'.

Manouch answered 20/7, 2011 at 10:58 Comment(9)
So what you end up with is... Not a class. You can't use it as a class, you can't base other classes upon it, you use import syntax, and all of a sudden you lose all the benefits of OOP...Pap
if you can base other classes on it, then it might not be a singleton. you could create one of the derived class, but also one of the base class, but the derived class is also a member of the base, and you have two of the base, which one are you supposed to use?Spurgeon
This doesn't work across modules. In my "main" module i set a value. I then reference it in another module and its null. Sigh.Vie
@PaulKenjora You must have an error in your code. If you define a global variable in a module, when you access it from another module it should have the value.Manouch
It has the value but when I change it it is not preserved. I ended up using a class with properties in a module that works. Simple types as globals did not work for me ( they lost values as soon as scope changed ).Vie
@Pap you could import * from base_module... rethink OOP my friend! hahahahHartsell
How could you init a singleton object with arguments in a module?Strauss
@Strauss pretty old, but you could introduce a third module config.py in which you can assign a variable: import c c.param = 10 import b b will import c and use c.param and it'll be 10, not ideal for some people but it worksEvening
A module is just a global. You're missing the case where you have a singleton per some predicate. E.g. getLogger has a singleton per namespaceRoderich
C
71

You probably never need a singleton in Python. Just define all your data and functions in a module and you have a de facto singleton:

import datetime
file_name=None

def set_file_name(new_file_name: str):
    global file_name
    file_name=new_file_name

def write(message: str):
    global file_name
    if file_name:
        with open(file_name, 'a+') as f:
            f.write("{} {}\n".format(datetime.datetime.now(), message))
    else:
        print("LOG: {}", message)

To use:

import log
log.set_file_name("debug.log")
log.write("System starting")
...

If you really absolutely have to have a singleton class then I'd go with:

class MySingleton(object):
    def foo(self):
        pass

my_singleton = MySingleton()

To use:

from mysingleton import my_singleton
my_singleton.foo()

where mysingleton.py is your filename that MySingleton is defined in. This works because after the first time a file is imported, Python doesn't re-execute the code.

Cyaneous answered 10/12, 2014 at 22:24 Comment(8)
Mostly true, but sometimes that's not enough. E.g. I have a project with a need to log instantiations of many classes at DEBUG level. I need command line options parsed at startup in order to set the user-specified logging level before those classes are instantiated. Module-level instantiations make that problematic. It's possible that I could carefully structure the app so that all of those classes don't get imported until the CLI processing is done, but natural structure of my app is more important than dogmatic adherence to "singletons are bad", since they can be done quite cleanly.Batho
if you were to test your code while patching my_singleton, would that be possible ? since this my_singleton could be instantiated in some other module.Pedro
@Pedro - my_singleton is a single object. If you "patch" it that change will affect all future references, even in other modules.Cyaneous
This might work in some cases, but sometimes lazy initialization is important. In my use case, initialization costs 400ms, so I don't want to incur that just because I imported the module. It has to be incurred only when the singleton is really needed.Mac
@joanis. Agreed there is no perfect solution for every possible use case. Maybe, you can still use lazy initialization for the time consuming part of your code, by not putting it into your constructor. Or maybe you need one of the other more complicated suggestions on this page.Cyaneous
Indeed, I've opted for a metaclass-based solution. It did the trick for me. Although it seems to verbose to me. In C++, I've used X* theX = NULL; X* getTheX() {if (theX == NULL) theX = new X(); return theX;}. Not very pythonic, but quite a bit shorter. I might switch to that with None and if theX is None instead, for code that I feel will be easier to read in the future.Mac
Would this solution be good for db connection handling? I would like to have just 1 place where my database connection is handled. My application uses multiprocessing with 100`s of threads that need to do batch executions in the database, so I am looking at ways to use resources more efficiently and thought about singletons, but not really sure they would work as intended in a multiprocessing app.Schaffner
@Schaffner If you have 100s of threads you probably want 100s of connections to the database. Also, if you are using CPython, you should understand the implications of the Python GIL. I don't know your use case, but likely performance would be a problem in such a model.Cyaneous
H
20

You just need a decorator, depending on the python version:


Python 3.2+

Implementation

from functools import lru_cache

@lru_cache(maxsize=None)
class CustomClass(object):

    def __init__(self, arg):
        print(f"CustomClass initialised with {arg}")
        self.arg = arg

Usage

c1 = CustomClass("foo")
c2 = CustomClass("foo")
c3 = CustomClass("bar")

print(c1 == c2)
print(c1 == c3)

Output

>>> CustomClass initialised with foo
>>> CustomClass initialised with bar
>>> True
>>> False

Notice how foo got printed only once


Python 3.9+

Implementation:

from functools import cache

@cache
class CustomClass(object):
    ...
Hekking answered 7/10, 2022 at 14:31 Comment(4)
The object won't be garbage collected in this case and you have to clear the cache (somewhere/sometime) if the class shouldn't life for the applications lifetime and is clearly a downside over the, already for this task, intended __new__ method.Mooned
@Mooned isn't the whole point of a singleton to stay in memory? If you garbage collect it, you effectively need to re-instantiate it if you need it again, which is the exact opposite of the goal here.Hekking
The term singleton describes that there is only one instance of it. Consider a larger application that uses the pattern in a "branch" and you keep accidentally a huge class in memory. I don't say your solution is a "no no" but it should be mentioned somewhere.Mooned
Also CustomClass is of type functools._lru_cache_wrapper, so you completely lose type information of the original class and isinstance(obj, CustomClass) doesn't work either.Dunston
R
18

Here's a one-liner for you:

singleton = lambda c: c()

Here's how you use it:

@singleton
class wat(object):
    def __init__(self): self.x = 1
    def get_x(self): return self.x

assert wat.get_x() == 1

Your object gets instantiated eagerly. This may or may not be what you want.

Rosenbaum answered 19/10, 2013 at 14:43 Comment(4)
Why do you need to know use the class of a singleton? Just use the singleton object..Word
It's not singleton pattern, so IMO the function should be named differently.Hyperploid
Wikipedia: "the singleton pattern is a design pattern that restricts the instantiation of a class to one object". I would say that my solution does just that. Okay, I guess one could do wat2 = type(wat)(), but this is python, we're all consenting adults and all that. You can't guarantee that there will be only one instance, but you can guarantee that if people make a second one, it will look ugly and—if they're decent, upstanding people—like a warning sign to them. What am I missing?Hinkley
if you are really looking for a one-line solution try a python's module as a singleton, which is actually a zero-line solution.Oxfordshire
E
10
  • If one wants to have multiple number of instances of the same class, but only if the args or kwargs are different, one can use the third-party python package Handy Decorators (package decorators).
  • Ex.
    1. If you have a class handling serial communication, and to create an instance you want to send the serial port as an argument, then with traditional approach won't work
    2. Using the above mentioned decorators, one can create multiple instances of the class if the args are different.
    3. For same args, the decorator will return the same instance which is already been created.
>>> from decorators import singleton
>>>
>>> @singleton
... class A:
...     def __init__(self, *args, **kwargs):
...         pass
...
>>>
>>> a = A(name='Siddhesh')
>>> b = A(name='Siddhesh', lname='Sathe')
>>> c = A(name='Siddhesh', lname='Sathe')
>>> a is b  # has to be different
False
>>> b is c  # has to be same
True
>>>
Elixir answered 1/8, 2019 at 10:37 Comment(3)
A need to make this kind of singleton is what led me to this question. Much appreciated! I tried pip install handy-decorators and I get ERROR: Could not find a version that satisfies the requirement handy-decorators. Any suggestion?Karyoplasm
I went ahead and copied the source code from here and decorated a dataclass. It worked the first time. Happily, it has no dependencies on any other code! Everything in that module is wonderfully simple and straightforward, truly Pythonic. If you aren't teaching Python, you should be.Karyoplasm
Caveat: The previous_instances dictionary of the implementation of @singleton does not look thread safe. If one thread is constructing an object while another object checks the dictionary, there is a race condition there...Malpighiaceous
S
10

Using a function attribute is also very simple

def f():
    if not hasattr(f, 'value'):
        setattr(f, 'value', singletonvalue)
    return f.value
Situate answered 2/7, 2020 at 9:35 Comment(0)
T
8

Here's my own implementation of singletons. All you have to do is decorate the class; to get the singleton, you then have to use the Instance method. Here's an example:

@Singleton
class Foo:
    def __init__(self):
        print 'Foo created'

f = Foo() # Error, this isn't how you get the instance of a singleton

f = Foo.Instance() # Good. Being explicit is in line with the Python Zen
g = Foo.Instance() # Returns already created instance

print f is g # True

And here's the code:

class Singleton:
    """
    A non-thread-safe helper class to ease implementing singletons.
    This should be used as a decorator -- not a metaclass -- to the
    class that should be a singleton.

    The decorated class can define one `__init__` function that
    takes only the `self` argument. Other than that, there are
    no restrictions that apply to the decorated class.
 
    To get the singleton instance, use the `Instance` method. Trying
    to use `__call__` will result in a `TypeError` being raised.

    Limitations: The decorated class cannot be inherited from.

    """

    def __init__(self, decorated):
        self._decorated = decorated

    def Instance(self):
        """
        Returns the singleton instance. Upon its first call, it creates a
        new instance of the decorated class and calls its `__init__` method.
        On all subsequent calls, the already created instance is returned.

        """
        try:
            return self._instance
        except AttributeError:
            self._instance = self._decorated()
            return self._instance

    def __call__(self):
        raise TypeError('Singletons must be accessed through `Instance()`.')

    def __instancecheck__(self, inst):
        return isinstance(inst, self._decorated)
Tamatave answered 20/9, 2011 at 18:4 Comment(1)
It's not true singleton. SingletonList = Singleton(list).Instance(); print(SingletonList is type(SingletonList)()) should print True in true singleton; with your code prints FalseHyperploid
B
8

I will recommend an elegant solution using metaclasses

class Singleton(type): 
    # Inherit from "type" in order to gain access to method __call__
    def __init__(self, *args, **kwargs):
        self.__instance = None # Create a variable to store the object reference
        super().__init__(*args, **kwargs)

    def __call__(self, *args, **kwargs):
        if self.__instance is None:
            # if the object has not already been created
            self.__instance = super().__call__(*args, **kwargs) # Call the __init__ method of the subclass (Spam) and save the reference
            return self.__instance
        else:
            # if object (Spam) reference already exists; return it
            return self.__instance

class Spam(metaclass=Singleton):
    def __init__(self, x):
        print('Creating Spam')
        self.x = x


if __name__ == '__main__':
    spam = Spam(100)
    spam2 = Spam(200)

Output:

Creating Spam

As you can see from the output, only one object is instantiated

Bop answered 19/8, 2020 at 8:42 Comment(0)
V
8

I prefer this solution which I found very clear and straightforward. It is using double check for instance, if some other thread already created it. Additional thing to consider is to make sure that deserialization isn't creating any other instances. https://gist.github.com/werediver/4396488

import threading


# Based on tornado.ioloop.IOLoop.instance() approach.
# See https://github.com/facebook/tornado
class SingletonMixin(object):
    __singleton_lock = threading.Lock()
    __singleton_instance = None

    @classmethod
    def instance(cls):
        if not cls.__singleton_instance:
            with cls.__singleton_lock:
                if not cls.__singleton_instance:
                    cls.__singleton_instance = cls()
        return cls.__singleton_instance


if __name__ == '__main__':
    class A(SingletonMixin):
        pass

    class B(SingletonMixin):
        pass

    a, a2 = A.instance(), A.instance()
    b, b2 = B.instance(), B.instance()

    assert a is a2
    assert b is b2
    assert a is not b

    print('a:  %s\na2: %s' % (a, a2))
    print('b:  %s\nb2: %s' % (b, b2))
Vina answered 26/10, 2020 at 21:53 Comment(6)
Pardon my ignorance, but why do you need to check twice for __singleton_instance? Could you not just always take __singleton_lock and then only check once?Pap
As I mentioned before, we need it to make sure that, while we are performing 'if' and using the lock, some other thread haven't created this instance already en.wikipedia.org/wiki/Double-checked_locking It's a fairly popular concept to be asked at interviews :)Vina
But surely the cost of acquiring an uncontested lock is low enough that if it were significant, you would be better off implementing it in C? IIRC the cost of acquiring the lock is about half that of a function call, and so the better optimisation here might be to avoid using the context manager and acquire the lock manually. If this is an unnecessary optimisation I'd argue double checking is even more so.Pap
Double checking is not an optimization, it is to make sure that we don't create two instances of a Singleton. It's also, good to point out that these checks will be executed only once, at the first initialization. After that it is just returning the instance. So any optimizations will be pointless.Vina
This is what I don't seem to be getting. Surely as long as you check while holding the lock you only need to check once? That's what the lock is there for, to synchronise access.Pap
Is double checking even needed for python ? that pattern is not about costs or optimization, but about memory model of the environment. The thing is, doesn't the GIL ensures proper locking when the object is being constructed ? There are languages in which the use of the double locking pattern is wrong, as there are reordering, besides, you don't always need it.Compunction
M
8

Use a class variable (no decorator)

By overriding the __new__ method to return the same instance of the class. A boolean to only initialize the class for the first time:

class SingletonClass:
    _instance = None

    def __new__(cls, *args, **kwargs):
        # If no instance of class already exits
        if cls._instance is None:
            cls._instance = object.__new__(cls)
            cls._instance._initialized = False
        return cls._instance
        
    def __init__(self, *args, **kwargs):
        if self._initialized:
            return

        self.attr1 = args[0]
        # set the attribute to `True` to not initialize again
        self._initialized = True
Mealtime answered 20/9, 2021 at 19:23 Comment(0)
V
6
from functools import cache

@cache
class xxx:
   ....

Dead easy and works!

Vicereine answered 3/11, 2021 at 19:20 Comment(1)
Careful - this only works if you don't pass any arguments on instantiation. If you do, it's a cache miss and you'll end up with multiple instances.Chapel
C
4

Method 3 seems to be very neat, but if you want your program to run in both Python 2 and Python 3, it doesn't work. Even protecting the separate variants with tests for the Python version fails, because the Python 3 version gives a syntax error in Python 2.

Thanks to Mike Watkins: http://mikewatkins.ca/2008/11/29/python-2-and-3-metaclasses/. If you want the program to work in both Python 2 and Python 3, you need to do something like:

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

MC = Singleton('MC', (object), {})

class MyClass(MC):
    pass    # Code for the class implementation

I presume that 'object' in the assignment needs to be replaced with the 'BaseClass', but I haven't tried that (I have tried code as illustrated).

Communitarian answered 24/7, 2013 at 17:6 Comment(2)
surely this is not a metaclass - in python3 to use a metaclass to construct MyClass you would do class MyClass(metaclass=Singleton)Pap
The mikewatkins.ca link is (effectively) broken.Anna
B
4

I'll toss mine into the ring. It's a simple decorator.

from abc import ABC

def singleton(real_cls):

    class SingletonFactory(ABC):

        instance = None

        def __new__(cls, *args, **kwargs):
            if not cls.instance:
                cls.instance = real_cls(*args, **kwargs)
            return cls.instance

    SingletonFactory.register(real_cls)
    return SingletonFactory

# Usage
@singleton
class YourClass:
    ...  # Your normal implementation, no special requirements.

Benefits I think it has over some of the other solutions:

  • It's clear and concise (to my eye ;D).
  • Its action is completely encapsulated. You don't need to change a single thing about the implementation of YourClass. This includes not needing to use a metaclass for your class (note that the metaclass above is on the factory, not the "real" class).
  • It doesn't rely on monkey-patching anything.
  • It's transparent to callers:
    • Callers still simply import YourClass, it looks like a class (because it is), and they use it normally. No need to adapt callers to a factory function.
    • What YourClass() instantiates is still a true instance of the YourClass you implemented, not a proxy of any kind, so no chance of side effects resulting from that.
    • isinstance(instance, YourClass) and similar operations still work as expected (though this bit does require abc so precludes Python <2.6).

One downside does occur to me: classmethods and staticmethods of the real class are not transparently callable via the factory class hiding it. I've used this rarely enough that I've never happen to run into that need, but it would be easily rectified by using a custom metaclass on the factory that implements __getattr__() to delegate all-ish attribute access to the real class.

A related pattern I've actually found more useful (not that I'm saying these kinds of things are required very often at all) is a "Unique" pattern where instantiating the class with the same arguments results in getting back the same instance. I.e. a "singleton per arguments". The above adapts to this well and becomes even more concise:

def unique(real_cls):

    class UniqueFactory(ABC):

        @functools.lru_cache(None)  # Handy for 3.2+, but use any memoization decorator you like
        def __new__(cls, *args, **kwargs):
            return real_cls(*args, **kwargs)

    UniqueFactory.register(real_cls)
    return UniqueFactory

All that said, I do agree with the general advice that if you think you need one of these things, you really should probably stop for a moment and ask yourself if you really do. 99% of the time, YAGNI.

Batho answered 27/8, 2016 at 22:22 Comment(0)
M
3

Maybe I missunderstand the singleton pattern but my solution is this simple and pragmatic (pythonic?). This code fullfills two goals

  1. Make the instance of Foo accessiable everywhere (global).
  2. Only one instance of Foo can exist.

This is the code.

#!/usr/bin/env python3

class Foo:
    me = None

    def __init__(self):
        if Foo.me != None:
            raise Exception('Instance of Foo still exists!')

        Foo.me = self


if __name__ == '__main__':
    Foo()
    Foo()

Output

Traceback (most recent call last):
  File "./x.py", line 15, in <module>
    Foo()
  File "./x.py", line 8, in __init__
    raise Exception('Instance of Foo still exists!')
Exception: Instance of Foo still exists!
Matrilineage answered 18/8, 2019 at 20:44 Comment(0)
M
3

Method: override __new__ after single use

class Singleton():
    def __init__(self):
        Singleton.instance = self
        Singleton.__new__ = lambda _: Singleton.instance

Pros

  • Extremely simple and concise
  • True class, no modules needed
  • Proper use of lambda and pythonic monkey patching

Cons

  • __new__ could be overridden again
Merideth answered 15/5, 2022 at 8:10 Comment(0)
F
2

Well, other than agreeing with the general Pythonic suggestion on having module-level global, how about this:

def singleton(class_):
    class class_w(class_):
        _instance = None
        def __new__(class2, *args, **kwargs):
            if class_w._instance is None:
                class_w._instance = super(class_w, class2).__new__(class2, *args, **kwargs)
                class_w._instance._sealed = False
            return class_w._instance
        def __init__(self, *args, **kwargs):
            if self._sealed:
                return
            super(class_w, self).__init__(*args, **kwargs)
            self._sealed = True
    class_w.__name__ = class_.__name__
    return class_w

@singleton
class MyClass(object):
    def __init__(self, text):
        print text
    @classmethod
    def name(class_):
        print class_.__name__

x = MyClass(111)
x.name()
y = MyClass(222)
print id(x) == id(y)

Output is:

111     # the __init__ is called only on the 1st time
MyClass # the __name__ is preserved
True    # this is actually the same instance
Friede answered 25/7, 2011 at 0:9 Comment(8)
What is the point of the _sealed attribute? As far as I see this doesn't do anything? Something is niggling me about this that says it shouldn't perform well... I'll run some comparative tests later this week.Pap
_sealed ensures your init is ran only once; I don't see any point why it should perform worse than the regular function-like decorator - the function is executed only once per class, and returns a new inherited classFriede
BTW, your edit contains tabs that break the indents You also say 'we are creating 2 classes' - do you mean that we are creating '1 extra class'?Friede
Yes one extra class is what I meant. I intend to include stuff in __init__ to be called every time it's initialised. Just a simple 'Being initialised in class.method'. as for indentation - you used tabs and spaces - I fixed most of it, but seem to have missed one if you want to get it (just check the edit log)Pap
re init: of course it's up to you, I just tried to mimic the singleton behavior in other languages, where constructor code (which is not exactly init, but very close in its sense) is only called once if you want the init to be called every time, just kill all references to _sealed re spaces / tabs - well, then my emacs needs fixing. anyway, above is the corrected versionFriede
@Friede I commented on your method in my post. Basically, the class shouldn't need to know / care it's a singleton. It should be able to customize __new__ and safely call super() -- which your method doesn't allow, as calling super() on a method of the same name will recurse.Vexillum
@agf, I think you are a bit exaggerating about names related to the inheritance chain: gist.github.com/1108823 We are just altering it's string name, not a class variableFriede
It's not the name of the class that matters. Try your own code: have MyClass.__init__(text) call super(MyClass, self).__init__(text) or add MyClass.__new__(cls) method and have it call return super(self, MyClass).__new__(cls). You'll recurse infinitely.Vexillum
W
2

How about this:

def singleton(cls):
    instance=cls()
    cls.__new__ = cls.__call__= lambda cls: instance
    cls.__init__ = lambda self: None
    return instance

Use it as a decorator on a class that should be a singleton. Like this:

@singleton
class MySingleton:
    #....

This is similar to the singleton = lambda c: c() decorator in another answer. Like the other solution, the only instance has name of the class (MySingleton). However, with this solution you can still "create" instances (actually get the only instance) from the class, by doing MySingleton(). It also prevents you from creating additional instances by doing type(MySingleton)() (that also returns the same instance).

Word answered 17/5, 2014 at 23:48 Comment(4)
You don't define a class to use it as an object.Epistasis
Every time you call type(MySingleton)(), MySingleton.__init__() gets called and the object gets initialized multiple Times; you can fix it writing cls.__init__ = lambda self: pass in your singleton. Also, overriding cls.__call__ seems pointless, and even harmful - __call__ defined in this context is used when you call MySingleton(any, list, of, arguments), not when you call type(MySingleton)(any, list, of, arguments).Hyperploid
@GingerPlusPlus, Thanks for pointing out that __init__() gets called again when doing type(MySingleton)(). The solution you proposed (adding cls.__init__ = lambda self: pass) give a syntax error, because the last part of the lambda expression needs to be an expression, not a statement. However, adding cls.__init__ = lambda self: None works, so I added that to my answer.Word
@GingerPlusPlus, Regarding the use of __call__. my intention was to make both type(MySingleton)() and MySingleton() return the instance. So it is doing what I wanted. You can think of MySingleton as either the type of the singleton or the instance of the singleton (or both).Word
L
2

It is slightly similar to the answer by fab but not exactly the same.

The singleton pattern does not require that we be able to call the constructor multiple times. As a singleton should be created once and once only, shouldn't it be seen to be created just once? "Spoofing" the constructor arguably impairs legibility.

So my suggestion is just this:

class Elvis():
    def __init__(self):
        if hasattr(self.__class__, 'instance'):
            raise Exception()
        self.__class__.instance = self
        # initialisation code...

    @staticmethod
    def the():
        if hasattr(Elvis, 'instance'):
            return Elvis.instance
        return Elvis()

This does not rule out the use of the constructor or the field instance by user code:

if Elvis() is King.instance:

... if you know for sure that Elvis has not yet been created, and that King has.

But it encourages users to use the the method universally:

Elvis.the().leave(Building.the())

To make this complete you could also override __delattr__() to raise an Exception if an attempt is made to delete instance, and override __del__() so that it raises an Exception (unless we know the program is ending...)

Further improvements


My thanks to those who have helped with comments and edits, of which more are welcome. While I use Jython, this should work more generally, and be thread-safe.

try:
    # This is jython-specific
    from synchronize import make_synchronized
except ImportError:
    # This should work across different python implementations
    def make_synchronized(func):
        import threading
        func.__lock__ = threading.Lock()
    
        def synced_func(*args, **kws):
            with func.__lock__:
                return func(*args, **kws)

        return synced_func

class Elvis(object): # NB must be subclass of object to use __new__
    instance = None

    @classmethod
    @make_synchronized
    def __new__(cls, *args, **kwargs):
        if cls.instance is not None:
            raise Exception()
        cls.instance = object.__new__(cls, *args, **kwargs)
        return cls.instance
    
    def __init__(self):
        pass
        # initialisation code...

    @classmethod
    @make_synchronized
    def the(cls):
        if cls.instance is not None:
            return cls.instance
        return cls()

Points of note:

  1. If you don't subclass from object in python2.x you will get an old-style class, which does not use __new__
  2. When decorating __new__ you must decorate with @classmethod or __new__ will be an unbound instance method
  3. This could possibly be improved by way of use of a metaclass, as this would allow you to make the a class-level property, possibly renaming it to instance
Louls answered 21/2, 2016 at 8:48 Comment(2)
Cool, the could probably benefit from being a class method for similar reasonsPap
yes, you're right. Then you can have a SuperElvis subclass singleton and (for example) an ImaginaryElvis subclass singleton... and they can co-exist. See additional thoughts. Please feel free to improve my code.Louls
T
2

This answer is likely not what you're looking for. I wanted a singleton in the sense that only that object had its identity, for comparison to. In my case it was being used as a Sentinel Value. To which the answer is very simple, make any object mything = object() and by python's nature, only that thing will have its identity.

#!python
MyNone = object()  # The singleton

for item in my_list:
    if item is MyNone:  # An Example identity comparison
        raise StopIteration
Toomin answered 29/9, 2016 at 18:40 Comment(4)
I have learned that modules can actually be imported multiple times, in such case this is only a local singleton, which isn't really a singleton in any capacity.Toomin
Can you elaborate on how a module can be imported multiple times? The only time I have seen that is when an exception occurs while the module is loaded, the user may still load the module later, yet the side effects will have occurred already, so some actions may be executed a second time.Stitch
Once a module has been fully loaded, I don't see a way to have this module run again, other than by coercing the interpreter into doing it using eval or importlib.reload.Stitch
@Stitch I thought I had an SO post on the topic, couldn't find it; here is a top google result: https://mcmap.net/q/18446/-python-how-to-load-a-module-twice IIRC I needed this to monkey patch some incorrect behavior in python's stdlib's ssl certificate chain of trust assertions when multiple domains were used in a particular way, allowing some modules to have their ssl interfaces replaced with the monkeypatched version and others to not, and being able to swap them as needed. I do not recommend monkey patching, but I'm sure glad the option exists :)Toomin
R
2

I also prefer decorator syntax to deriving from metaclass. My two cents:

from typing import Callable, Dict, Set


def singleton(cls_: Callable) -> type:
    """ Implements a simple singleton decorator
    """
    class Singleton(cls_):  # type: ignore
        __instances: Dict[type, object] = {}
        __initialized: Set[type] = set()

        def __new__(cls, *args, **kwargs):
            if Singleton.__instances.get(cls) is None:
                Singleton.__instances[cls] = super().__new__(cls, *args, **kwargs)
            return Singleton.__instances[cls]

        def __init__(self, *args, **kwargs):
            if self.__class__ not in Singleton.__initialized:
                Singleton.__initialized.add(self.__class__)
                super().__init__(*args, **kwargs)

    return Singleton


@singleton
class MyClass(...):
    ...

This has some benefits above other decorators provided:

  • isinstance(MyClass(), MyClass) will still work (returning a function from the clausure instead of a class will make isinstance to fail)
  • property, classmethod and staticmethod will still work as expected
  • __init__() constructor is executed only once
  • You can inherit from your decorated class (useless?) using @singleton again

Cons:

  • print(MyClass().__class__.__name__) will return Singleton instead of MyClass. If you still need this, I recommend using a metaclass as suggested above.

If you need a different instance based on constructor parameters this solution needs to be improved (solution provided by siddhesh-suhas-sathe provides this).

Finally, as other suggested, consider using a module in python. Modules are objects. You can even pass them in variables and inject them in other classes.

Rhonarhonchus answered 7/12, 2020 at 14:23 Comment(0)
S
2

Pros

It's a true class Auto-magically covers inheritance Uses metaclass for its proper purpose (and made me aware of it) Cons

Are there any?

This will be problem with serialziation. If you try to deserialize object from file (pickle) it will not use __call__ so it will create new file, you can use base class inheritance with __new__ to prevent that.

Sacral answered 6/3, 2021 at 19:21 Comment(0)
M
2

You can use a metaclass if you want to use instance as a property. For example;

class SingletonMeta(type):
    def __init__(cls, *args, **kwargs):
        super().__init__(*args, **kwargs)
        cls._instance = None
        cls._locker = threading.Lock()

    @property
    def instance(self, *args, **kwargs):
        if self._instance is None:
            with self._locker:
                if self._instance is None:
                    self._instance = self(*args, **kwargs)
        return self._instance


class MyClass(metaclass=SingletonMeta):
    def __init__(self):
        # init here
        pass


# get the instance
my_class_instance = MyClass.instance
Melody answered 10/3, 2021 at 16:18 Comment(1)
And what's happen when we call MyClass twice ? I got two different adress here...It does not seem to avoid new instancesHendecahedron
O
2

I just made a simple one by accident and thought I'd share it...

class MySingleton(object):
    def __init__(self, *, props={}):
        self.__dict__ = props

mything = MySingleton()
mything.test = 1
mything2 = MySingleton()
print(mything2.test)
mything2.test = 5
print(mything.test)
Oscitant answered 5/8, 2021 at 21:16 Comment(0)
V
1

I can't remember where I found this solution, but I find it to be the most 'elegant' from my non-Python-expert point of view:

class SomeSingleton(dict):
    __instance__ = None
    def __new__(cls, *args,**kwargs):
        if SomeSingleton.__instance__ is None:
            SomeSingleton.__instance__ = dict.__new__(cls)
        return SomeSingleton.__instance__

    def __init__(self):
        pass

    def some_func(self,arg):
        pass

Why do I like this? No decorators, no meta classes, no multiple inheritance...and if you decide you don't want it to be a Singleton anymore, just delete the __new__ method. As I am new to Python (and OOP in general) I expect someone will set me straight about why this is a terrible approach?

Votyak answered 11/11, 2014 at 5:38 Comment(3)
why this is a terrible approach? when you want create another singleton class, you have to copy & paste the __new__. Don't repeat yourself.Hyperploid
Also, why your new takes *args and **kwargs, and then does nothing with them? Pass them into dict.__new__ this way: dict.__new__(cls, *args, **kwargs).Hyperploid
This will call the __init__ method every time the class is called. If your __init__ method actually did something, you'd notice the problem. Whenever you do SomeSingleton(), your singleton's state is reset by the __init__ method.Buckle
H
1

Code based on Tolli's answer.

#decorator, modyfies new_cls
def _singleton(new_cls):
    instance = new_cls()                                              #2
    def new(cls):
        if isinstance(instance, cls):                                 #4
            return instance
        else:
            raise TypeError("I can only return instance of {}, caller wanted {}".format(new_cls, cls))
    new_cls.__new__  = new                                            #3
    new_cls.__init__ = lambda self: None                              #5
    return new_cls


#decorator, creates new class
def singleton(cls):
    new_cls = type('singleton({})'.format(cls.__name__), (cls,), {} ) #1
    return _singleton(new_cls)


#metaclass
def meta_singleton(name, bases, attrs):
    new_cls = type(name, bases, attrs)                                #1
    return _singleton(new_cls)

Explanation:

  1. Create new class, inheriting from given cls
    (it doesn't modify cls in case someone wants for example singleton(list))

  2. Create instance. Before overriding __new__ it's so easy.

  3. Now, when we have easily created instance, overrides __new__ using method defined moment ago.
  4. The function returns instance only when it's what the caller expects, otherwise raises TypeError.
    The condition is not met when someone attempts to inherit from decorated class.

  5. If __new__() returns an instance of cls, then the new instance’s __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to __new__().

    instance is already initialized, so function replaces __init__ with function doing nothing.

See it working online

Hyperploid answered 30/12, 2014 at 21:47 Comment(0)
H
1

One liner (I am not proud, but it does the job):

import sys

class Myclass:
  def __init__(self):
     # do your stuff
      vars(sys.modules[__name__])[type(self).__name__] = lambda: self # singletonify
Hartsell answered 7/3, 2018 at 4:50 Comment(0)
S
1

If you don't need lazy initialization of the instance of the Singleton, then the following should be easy and thread-safe:

class A:
    instance = None
    # Methods and variables of the class/object A follow
A.instance = A()

This way A is a singleton initialized at module import.

Scamp answered 1/1, 2019 at 19:45 Comment(0)
J
1

After struggling with this for some time I eventually came up with the following, so that the config object would only be loaded once, when called up from separate modules. The metaclass allows a global class instance to be stored in the builtins dict, which at present appears to be the neatest way of storing a proper program global.

import builtins

# -----------------------------------------------------------------------------
# So..... you would expect that a class would be "global" in scope, however
#   when different modules use this,
#   EACH ONE effectively has its own class namespace.  
#   In order to get around this, we use a metaclass to intercept
#   "new" and provide the "truly global metaclass instance" if it already exists

class MetaConfig(type):
    def __new__(cls, name, bases, dct):
        try:
            class_inst = builtins.CONFIG_singleton

        except AttributeError:
            class_inst = super().__new__(cls, name, bases, dct)
            builtins.CONFIG_singleton = class_inst
            class_inst.do_load()

        return class_inst

# -----------------------------------------------------------------------------

class Config(metaclass=MetaConfig):

    config_attr = None

    @classmethod
    def do_load(cls):
        ...<load-cfg-from-file>...
Jurisprudent answered 18/10, 2019 at 14:24 Comment(0)
T
1

Few caveats I would want to highlight is,

  1. metaclass approach:
  • You can not inherit from 2 metaclasses. Check
  • In case if you are using a factory pattern all of which are singleton classes then it wont work.
  • Your parent is already inheriting from ABC (which is metaclass) then you can not inherit from singleton metaclass
  1. Decorator approach:
  • I was using a function as factory interface which creates an instance of T from base.__subclasses__().
  • This will skip the singleton decorator for the subclass initialization
Theotokos answered 3/7, 2022 at 20:59 Comment(0)
R
1

I used this:

def singleton(cls):
    instances = dict()

    def __new__(klass, *args, **kwargs):
        klass_path = klass.__module__ + '.' + klass.__name__
        instance = instances.get(klass_path, None)
        if instance is not None:
            return instance

        attributes = dict(klass.__dict__)
        attributes.pop('__new__')

        klass = type(klass.__name__, klass.__bases__, attributes)
        instances[klass_path] = klass(*args, **kwargs)
        return instances[klass_path]

    cls.__new__ = __new__
    return cls


@singleton
class ABC:
    pass


@singleton
class QWERTY:
    pass


print('id:', id(ABC()))
print('id:', id(ABC()))
print('id:', id(QWERTY()))
print('id:', id(QWERTY()))

The output is so:

id: 4396645488
id: 4396645488
id: 4396790976
id: 4396790976
Rea answered 6/11, 2023 at 19:50 Comment(0)
C
1

Enum with a single member

This seems to be lightweight solution that has not been mentioned yet:

from enum import Enum

class Default(Enum):
    INSTANCE = None

    @staticmethod
    def foo():
        return "foo"

    @classmethod
    def bar(cls):
        return "bar"

o = Default.INSTANCE
assert Default(o) is o
assert Default(None) is o
assert o.foo() == "foo"
assert o.bar() == "bar"

Using an Enum class as a singleton class is also suggested in PEP 484 -- Type Hints.

Unfortunately, if the Enum-based singleton needs to inherit from some abstract class, you need to jump through some hoops:

Chastise answered 18/2 at 8:58 Comment(1)
Attrs changed to this recently: github.com/python-attrs/attrs/blob/main/src/attr/…Soelch
L
0

Here is simple implementation combining @agf and @(Siddhesh Suhas Sathe) solutions, where it uses metaclass and take into consideration the constructor args so you can return the same instance if you created the foo class with the exact same args


class SingletonMeta(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        """
        Possible changes to the value of the `__init__` argument do not affect
        the returned instance.
        """
        cls_instances = cls._instances.get(cls) or []
        matching_instances = list(
            filter(
                lambda x: x["args"] == args and x["kwargs"] == kwargs,
                cls_instances,
            )
        )
        if len(matching_instances) == 1:
            return matching_instances[0]["instance"]
        else:
            instance = super().__call__(*args, **kwargs)
            cls_instances.append({"instance": instance, "args": args, "kwargs": kwargs})
            cls._instances[cls] = cls_instances
            return instance


class foo(metaclass=SingletonMeta):
    def __init__(self, param, k_param=None) -> None:
        print("Creating new instance")
        self.param = param
        self.k_param = k_param
        self._creation_time = time.time()
Lewse answered 17/11, 2021 at 16:12 Comment(0)
R
0

I prefer to use a static method GetInstance() to create a singleton object (also not allow any other method to do that) to emphasize that I am using a singleton design pattern.

import inspect
class SingletonMeta(type):
    __instances = {}
    GET_INSTANCE = 'GetInstance' # class method ussed to create Singleton instance

    def __call__(cls, *args, **kwargs):
        caller_frame = inspect.currentframe().f_back

        caller_class = caller_frame.f_locals.get('cls_ref')
        caller_method_name = caller_frame.f_code.co_name
        if caller_class is cls and \
            caller_method_name == SingletonMeta.GET_INSTANCE:
            obj = super(SingletonMeta, cls).__call__(*args, **kwargs)
        else:
            raise Exception(f"Class '{cls.__name__}' is a singleton! Use '{cls.__name__}.{SingletonMeta.GET_INSTANCE}()' to create its instance.")

        return obj

    def __new__(cls, name, bases, dct):
        def GetInstance(cls_ref):
            if cls_ref not in cls_ref.__instances:
                cls_ref.__instances[cls_ref] = cls_ref()

            return cls_ref.__instances[cls_ref]
       
        return super().__new__(cls, name, bases, {**dct, GetInstance.__name__: classmethod(GetInstance)})
#------------------------
if __name__ == '__main__':
    class SingletonSample1(metaclass=SingletonMeta):
        def __init__(self):
            self.__x = 1

        @property
        def x(self) -> int:
            return self.__x

        @x.setter
        def x(self, value):
            self.__x = value

    s1 = SingletonSample1.GetInstance()
    s1.x = 3

    try:
        s2 = SingletonSample1()
    Exception as error:
        print(repr(error))
Rateable answered 29/1, 2022 at 15:5 Comment(0)
S
0

I want to point out that the first method defines a dictionary for lookup, which I until today do not understand, and I see this solution spreading all over the place, so I guess everyone just copy pastes it from here.

I am talking about this one:

def singleton(class_):
    instances = {} # <-- will always only have one entry.
    def getinstance(*args, **kwargs):
        if class_ not in instances:
            instances[class_] = class_(*args, **kwargs)
        return instances[class_]
    return getinstance

It makes sense for metaclass solutions, but with the one-off decorator solution, each time the decorator is called, a new function gets defined, as well as a new instances variable, so each "instances" will always only have one entry, except if you make it global. It will also not work with inheritance anyway.

A similar, but simpler, and also better adjustable solution:

def singleton(class_):
    def wrapper(*args, **kwargs):
        if not wrapper._instance:
            wrapper._instance = class_(*args, **kwargs)
        return wrapper._instance

    wrapper._instance = None
    return wrapper

adding a simple

    ...
    wrapper.__wrapped__ = class_
    return wrapper

as well also allows inheritance or mocking, by accessing __wrapped__, which is also not possible with the inner dict lookup.

(Of course pardon me, if I simply did not understand the mystery behind the dictionary lookup. Maybe it is my fault for not understanding the particular intent behind it)

Scarce answered 20/4, 2022 at 16:18 Comment(0)
H
0

As @Staale mentions here, the simplest way to make a singleton in python is to use a module with global variables (as 'attributes' & global functions as 'methods'). BUT I would like to add something very important to this already amazing answer: inheritance works here too!

All you need to do to make a 'singleton module' B.py that inherits from another 'singleton module' A.py is start B.py with the line: from A import *, this respects private variables (by not importing them by default).

Haro answered 30/5, 2022 at 20:0 Comment(0)
B
0

Honestly, I found a very simple solution:

@lambda x: x()
class ClassA:
    ...

This does make ClassA an instance of ClassA and makes the uninstanciated class inaccessible. If you want something a bit more flexible you can define a method like so:

def singleton(*args, **kwargs):
    def _decorator(cls):
        return cls(*args, **kwargs)
    return decorator

@singleton(...)
class ClassA:
    def __init__(self, ...):
        ...

Althogh I can't imagine why you'd add arguments to your init class if you want a singleton, so let's simplify this to this function, which is the same as the lambda but cleaner:

def singleton(cls):
    return cls()
Behka answered 21/8, 2023 at 10:55 Comment(0)
H
0

Use undecorated static methods

I don't know if I'm missing something here, but what about using undecorated static methods?

By referring to Is @staticmethod decorator needed for declaring a Static Method in Python? and @staticmethod vs @classmethod in Python it seems that not having any decorator, which would fail if called on an object, is the desired behavior here for a singleton:

  • No need to instantiate the singleton
  • No need to call get_instance()
  • Just use the singleton name, which for example in this case is Day:
class Day():
  # Class variable
  dow = {
    0: 'Sun',
    1: 'Mon',
    2: 'Tue',
    3: 'Wed'
  }

  # Called when a class is instantiated as an object
  def __init__(self):
    raise 'You should not instantiate a Singleton'

  # # Should not define instance methods
  # def instance_method(self):
  #   return self
    
  # static method, undecorated
  #   works when called from class
  #   fails when called from object (because it is called with 'self') and this failure is desired
  def day(d):
    day= 'X' # Not found
    try:
      day =  Day.dow[d]
    except:
      pass
    return day
  
  def add_day():
    for d in Day.dow:
      Day.dow[d] = f'{Day.dow[d]}day'


def main():
  print('Static Method, undecorated')
  print('--------------------------')
  day = Day.day(1) # Call static method of singleton
  print(f'day={day}')

  Day.add_day()    # Call another static method of singleton to change its state and messup the names of the days

  day = Day.day(1) # Call static method of singleton after state change
  print(f'day={day}')

  # obj = Day()    # Do not instantiate singleton as object

  print('\nClass variable')
  print('--------------')
  print(f'dow={Day.dow}')

if __name__ == '__main__':
    main()

This gives me the desired output:

Static Method, undecorated
--------------------------
day=Mon
day=Monday

Class variable
--------------
dow={0: 'Sunday', 1: 'Monday', 2: 'Tueday', 3: 'Wedday'}
Hy answered 9/10, 2023 at 22:49 Comment(0)
K
0

I know I am probably late to the party, but I think the metaclass approach can be improved. We don't need a dictionary to map the class to its singleton instance. We can simply have the singleton instance as an attribute of the class. Remember that instances of a metaclass are classes, so instance attributes of a metaclass are class attributes (static attributes for anyone coming from Java or C#). Here's the implementation:

class Singleton(type):
    _instance = None  # This is an attribute of the class

    def __call__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__call__(*args, **kwargs)
            return cls._instance
        name = cls.__name__
        raise RuntimeError(
            f"{name} already created. use {name}.get() to get the {name} instance."
        )

    def get(cls):
        return cls._instance


class Foo(metaclass=Singleton):
    def __init__(self, a, b):
        self.a = a
        self.b = b


class Bar(metaclass=Singleton):
    def __init__(self, a, b):
        self.a = a
        self.b = b


f = Foo(1, 2)
print(f)
print(f.a, f.b)
print(Foo.get() is f)
# f2 = Foo(3, 4)  # error

b = Bar(3, 4)
print(b)
print(b.a, b.b)
print(Bar.get() is b)
b.a = 5
# b2 = Bar(3, 4)  # error

print("Foo", f.a, f.b)
print("Bar", b.a, b.b)

This code prints:

<__main__.Foo object at 0x00000224A192FD90>
1 2
True
<__main__.Bar object at 0x00000224A192FE10>
3 4
True
Foo 1 2
Bar 5 4

As you can see, each class gets its own single _instance which needs to be instantiated as normal and can later be accessed with a get() class method. Trying to create another instance will raise a RuntimeError.

Of course, you can modify the code to return the existing instance if already been created instead of raising an error, and you can implement __new__(cls, *args, **kwargs) to create the instance immediately when the class is defined instead of lazily when the constructor is first called, but these are easy modifications you can do to suit your needs.

This removes the need for a dictionary that maps classes to their singleton instance like in the question and in the first answer. This results in a simpler implementation and probably a slightly faster one since we use simple attribute access instead of dictionary access (I didn't run any benchmarks so don't quote me on that).

Khalid answered 10/10, 2023 at 8:53 Comment(0)
E
0

You don't need it. Python's imported objects are already "singletons". When you have a file mymodule.py defining

myobject = MyClass(...)

and you write from mymodule import myobject in multiple places, the code is imported/executed only the first time. All subsequent imports will use the same instance, that is cached in sys.imports.

So, you don't need that pattern in the way you need it eg. Java, where you can't import already instantiated objects.

Extort answered 11/3 at 9:56 Comment(0)
N
-2

This solution causes some namespace pollution at the module level (three definitions rather than just one), but I find it easy to follow.

I'd like to be able to write something like this (lazy initialization), but unfortunately classes are not available in the body of their own definitions.

# wouldn't it be nice if we could do this?
class Foo(object):
    instance = None

    def __new__(cls):
        if cls.instance is None:
            cls.instance = object()
            cls.instance.__class__ = Foo
        return cls.instance

Since that isn't possible, we can break out the initialization and the static instance in

Eager Initialization:

import random


class FooMaker(object):
    def __init__(self, *args):
        self._count = random.random()
        self._args = args


class Foo(object):
    def __new__(self):
        return foo_instance


foo_instance = FooMaker()
foo_instance.__class__ = Foo

Lazy initialization:

Eager Initialization:

import random


class FooMaker(object):
    def __init__(self, *args):
        self._count = random.random()
        self._args = args


class Foo(object):
    def __new__(self):
        global foo_instance
        if foo_instance is None:
            foo_instance = FooMaker()
        return foo_instance


foo_instance = None
Nagari answered 20/7, 2011 at 10:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.