By theheadofabroom


2011-07-20 10:47:57 8 Comments

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 a function, not a class, so you cannot call class methods from it. Also for m = MyClass(); n = MyClass(); o = type(n)(); then m == n && m != o && n != o

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

23 comments

@Ruben Decrop 2020-07-02 09:35:48

Using a function attribute is also very simple

def f():
    if not hasattr(f, 'value'):
        setattr(f, 'value', singletonvalue)
    return f.value

@Siddhesh Suhas Sathe 2019-08-01 10:37:27

  • 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
>>>

@agf 2011-07-23 03:28:20

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 it's 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 it's 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 it's 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.

@Cat Plus Plus 2011-07-23 11:32:51

No, singletons are never good. Logging might be a good candidate for being a global (as terrible as they are), but certainly not singleton.

@agf 2011-07-23 11:36:14

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.

@Cat Plus Plus 2011-07-23 11:46:58

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.

@theheadofabroom 2011-07-24 16:42:42

@agf I'll probably accept and award this answer, but shall give a little time for others. I've not worked with metaclasses before, and although I've had a quick google, the answer may be more valuable to future readers if some more explanation could be given on how these are used, what they effect, and any pitfalls to watch out for.

@agf 2011-07-28 02:17:28

@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.

@Paul Manta 2011-08-06 13:47:19

@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).

@Paul Manta 2011-08-06 13:51:43

@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...

@Alcott 2011-09-20 06:25:26

@agf, when implementing Singleton through metaclass, why did you use "call" not "new"? and What's the difference?

@agf 2011-09-20 06:28:48

@Alcott __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-examp‌​le. A good article on singletons is the series from the google blog I linked in this answer.

@agf 2011-09-20 06:30:38

Also, see stackoverflow.com/questions/31875/… for more singleton stuff if you haven't found that yet.

@agf 2012-12-09 22:34:59

@martineau It's an easy mistake to make. Python 3 has improved the metaclass syntax by making it a keyword argument: Logger(metaclass = Singleton).

@FichteFoll 2014-10-01 01:31:25

Instead of class Singleton(_Singleton('SingletonMeta', (object,), {})): pass you could remove one class by using an assignment: Singleton = _Singleton('Singleton', (object,), {}).

@Malina 2015-02-24 17:33:02

@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).

@Eastsun 2015-05-24 05:01:56

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.

@agf 2015-05-24 18:38:18

@Eastsun 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.

@Jonathan 2015-09-02 23:29:17

@Christophe, consider also inheritance. Perhaps an App singleton, and lots of different types of Apps that inherent from that (LinuxApp, MobileApp, DesktopApp) etc

@Pankaj Singhal 2016-08-19 08:22:17

@agf I want to return object on the basis of arguments, not on class name basis. Can someone provide a solution of my question which I've posted here -> stackoverflow.com/questions/39033946/…

@Chen A. 2017-09-24 07:27:02

@agf 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?

@agf 2017-09-24 15:25:23

@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.

@agf 2017-09-24 15:26:02

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.

@Chen A. 2017-09-24 20:18:56

@agf 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 :-)

@agf 2017-12-18 01:34:37

@MichaelBerdyshev It should in Python 3.

@user2128702 2018-08-25 13:56:49

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.

@astafan8 2019-03-07 13:28:38

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.

@Den-Jason 2019-10-18 14:24:05

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>...

@buhtz 2019-08-18 20:44:52

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!

@Serge Rogatch 2019-01-01 19:45:30

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.

@polvoazul 2018-03-07 04:50:31

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

class Myclass:
  def __init__(self):
      # do your stuff
      globals()[type(self).__name__] = lambda: self # singletonify

@Aran-Fey 2018-10-24 12:41:32

This may do the job as long as your class hasn't been imported into any other modules...

@polvoazul 2018-10-26 14:56:43

True. If you can pay the cost of initing the class you can run a Myclass() immediately after the class definition to avoid this.

@Gregory Nisbet 2016-10-31 22:07:59

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

@ThorSummoner 2016-09-29 18:40:06

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

@ThorSummoner 2018-03-23 20:00:35

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.

@sleblanc 2019-03-16 15:25:52

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.

@sleblanc 2019-03-16 15:29:11

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.

@CryingCyclops 2016-08-27 22:22:33

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.

@Alan Dyke 2014-12-10 22:24:14

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.

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

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

my_singleton = My_Singleton()

To use:

from mysingleton import my_singleton
my_singleton.foo()

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

@CryingCyclops 2016-08-27 21:29:54

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.

@Naveen 2018-04-24 03:04:56

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.

@Alan Dyke 2018-04-24 19:30:17

@Naveen - my_singleton is a single object. If you "patch" it that change will affect all future references, even in other modules.

@Tim 2013-07-24 17:06:05

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).

@theheadofabroom 2013-07-30 14:32:55

surely this is not a metaclass - in python3 to use a metaclass to construct MyClass you would do class MyClass(metaclass=Singleton)

@Peter Mortensen 2016-03-14 21:54:33

The mikewatkins.ca link is (effectively) broken.

@Anton 2011-07-20 11:00:17

Check out Stack Overflow question Is there a simple, elegant way to define singletons in Python? with several solutions.

I'd strongly recommend to watch Alex Martelli's talks on design patterns in python: part 1 and part 2. In particular, in part 1 he talks about singletons/shared state objects.

@theheadofabroom 2011-07-25 13:08:32

While this is not really an answer to my question, the resources you point to are very useful. I begrudgingly give you a +1

@mike rodent 2016-02-21 08:48:18

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

The singleton contract 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

@theheadofabroom 2016-02-21 09:40:38

While this is a slightly different interpretation of the singleton pattern, I'm pretty sure it's still valid, although I might be tempted to use __new__ rather than __init__, as it purely acts on class attributes and this prevents there from briefly being a second instance. The difference then between this and method 2, is whether trying to initialise more than once returns the single instance or raises an exception. I think I'm happy that either satisfy the singleton pattern, one is easier to use, while the other is more explicit that it is a singleton.

@theheadofabroom 2016-02-21 09:43:29

Obviously use of the class name in __init__ prevents subclassing, but while this makes things easier, it's not required

@mike rodent 2016-02-21 09:51:34

Thanks... ah yes, a momentary second instance before the Exception gets thrown. I have modified the __init__ so that hopefully this should be subclassable...

@theheadofabroom 2016-02-21 10:32:02

Cool, the could probably benefit from being a class method for similar reasons

@mike rodent 2016-02-21 11:35:10

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.

@mike rodent 2016-02-22 18:09:49

Thanks for the code improvements. Just one minor quibble/doubt: making instance a class field like this means that King.instance evaluates to None before the singleton is created, rather than raising a "no attribute" exception... Never mind though. Arguably more desirable: I don't know what reasoning to apply...

@mike rodent 2016-02-22 18:22:09

oops, also had to tweak your the version to reflect use of class field

@mike rodent 2017-12-23 08:20:44

2017-12-23 downvote... please have the courtesy to add a comment to explain your thinking: it might be helpful to me, or you might find that you learn something

@Tolli 2014-05-17 23:48:58

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).

@0xc0de 2014-10-16 08:00:39

You don't define a class to use it as an object.

@GingerPlusPlus 2014-12-31 13:23:48

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).

@Tolli 2015-01-02 05:42:55

@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.

@Tolli 2015-01-02 05:43:19

@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).

@GingerPlusPlus 2014-12-30 21:47:44

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

@2cynykyl 2014-11-11 05:38:12

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?

@GingerPlusPlus 2014-12-30 17:56:18

why this is a terrible approach? when you want create another singleton class, you have to copy & paste the __new__. Don't repeat yourself.

@GingerPlusPlus 2014-12-31 13:29:52

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).

@Aran-Fey 2018-10-24 12:45:30

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.

@fab 2014-10-29 23:12:22

This is my preferred way of implementing singletons:

class Test(object):
    obj = None

    def __init__(self):
        if Test.obj is not None:
            raise Exception('A Test Singleton instance already exists')
        # Initialization code here

    @classmethod
    def get_instance(cls):
        if cls.obj is None:
            cls.obj = Test()
        return cls.obj

    @classmethod
    def custom_method(cls):
        obj = cls.get_instance()
        # Custom Code here

@theheadofabroom 2014-10-30 08:21:09

This is not strictly a singleton as it allows for more than one instance of the class to exist. An improvement would be to make the class unable to be initialised, and have all class methods act on class attributes

@Jonas Kölker 2013-10-19 14:43:33

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.

@0xc0de 2014-10-16 07:56:57

-1. This is very bad and silly. You don't define a class to use as an object. You can no longer access the class without being very ugly like type(wat) or wat.__class__. If you really want to achieve this, better define the class and instantiate it right away, no need to mess up with the decorator.

@Tolli 2014-10-17 23:41:03

Why do you need to know use the class of a singleton? Just use the singleton object..

@GingerPlusPlus 2014-12-30 21:53:01

It's not singleton pattern, so IMO the function should be named differently.

@Jonas Kölker 2015-01-02 19:35:11

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?

@Paul Manta 2011-09-20 18:04:41

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)

@GingerPlusPlus 2014-12-30 22:07:19

It's not true singleton. SingletonList = Singleton(list).Instance(); print(SingletonList is type(SingletonList)()) should print True in true singleton; with your code prints False

@Paul Manta 2014-12-30 22:19:01

@GingerPlusPlus I was aware of a few limitations, but not of the one you pointed out. Thanks for mentioning it. Unfortunately, I don't have time at the moment to thin about a solution to this.

@Guard 2011-07-25 00:09:34

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

@theheadofabroom 2011-07-25 10:32:45

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.

@Guard 2011-07-25 19:29:17

_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 class

@Guard 2011-07-25 19:31:34

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'?

@theheadofabroom 2011-07-26 06:33:22

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)

@Guard 2011-07-26 06:52:49

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 version

@agf 2011-07-27 05:20:21

@Guard 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.

@Guard 2011-07-27 06:59:00

@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 variable

@agf 2011-07-27 07:23:48

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.

@ovgolovin 2012-08-04 20:33:08

@agf Could you explain why super(MyClass, self).__init__(text) recurses? As I understand, super(MyClass, self) should be object.

@ovgolovin 2012-08-04 20:57:29

@agf I made a special question for that: stackoverflow.com/questions/11811935/…

@warvariuc 2011-07-20 10:58:19

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'.

@theheadofabroom 2011-07-25 13:04:28

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...

@SingleNegationElimination 2011-07-25 19:32:13

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?

@Paul Kenjora 2017-03-30 14:20:59

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.

@warvariuc 2017-03-30 19:40:42

@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.

@Paul Kenjora 2017-04-13 18:32:45

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 ).

@polvoazul 2018-03-07 04:46:37

@theheadofabroom you could import * from base_module... rethink OOP my friend! hahahah

@nn0p 2019-06-10 04:51:05

How could you init a singleton object with arguments in a module?

@Cat Plus Plus 2011-07-20 10:52:04

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.

@Alcott 2011-09-20 01:30:48

why did you say "Don't use singletons"? Any reason?

@dividebyzero 2012-01-20 11:47:56

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; # False

@Jonas Kölker 2014-02-17 10:52:56

@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.

@Dan Passaro 2014-04-28 17:16:32

@JonasKölker pickle.loads() does do that already, e.g. for instances of bool and NoneType. pickle.loads(pickle.dumps(False)) is False yields True

@Jonas Kölker 2014-05-03 00:18:10

@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.)

@deepak 2016-06-21 11:25:13

@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.

@Jan DB 2017-10-11 12:19:58

This only works if all the imports happen the same way. import project.module and import .module will run the code twice.

@Naveen 2018-04-24 04:07:36

If some_global_variable is used in some_module.py and that was the module under test, would mocking some_global_variable be possible?

@joel 2019-08-04 11:30:51

should Foo be __Foo so that users won't casually just use that?

Related Questions

Sponsored Content

22 Answered Questions

[SOLVED] What are metaclasses in Python?

42 Answered Questions

[SOLVED] How to get the current time in Python

  • 2009-01-06 04:54:23
  • user46646
  • 3344280 View
  • 2947 Score
  • 42 Answer
  • Tags:   python datetime time

25 Answered Questions

[SOLVED] How can I safely create a nested directory?

26 Answered Questions

[SOLVED] Does Python have a ternary conditional operator?

39 Answered Questions

[SOLVED] Difference between static class and singleton pattern?

61 Answered Questions

[SOLVED] Calling an external command from Python

10 Answered Questions

[SOLVED] Does Python have a string 'contains' substring method?

Sponsored Content