1

I already read many articles that explain how to implement singleton in python,like Creating a singleton in Python

I was wondering, isn't a class with class methods and attributes is a singleton class.

e.g.

class my_singleton_class(object):

    _logger = Logger ()   
    _printer = Printer ()

    @classmethod
    def logger(cls):
        return cls._logger

    @classmethod
    def printer(cls):
        return cls._printer

Is it not pythonic ? What is wrong with this singleton implementation ?

Community
  • 1
  • 1
deepak
  • 317
  • 4
  • 15
  • You should take a look at this: http://stackoverflow.com/questions/1318406/why-is-the-borg-pattern-better-than-the-singleton-pattern-in-python – phogl Jun 21 '16 at 11:55

2 Answers2

6

I was wondering, isn't a class with class methods and attributes is a singleton class.

No.

By definition a singleton class is a class which you can't create more than 1 instance of.

Let's put it to the test:

class my_singleton_class(object):
    _logger = 1
    _printer = 2

    @classmethod
    def logger(cls):
        return cls._logger

    @classmethod
    def printer(cls):
        return cls._printer

print(id(my_singleton_class()))
print(id(my_singleton_class()))
>> 8322128
>> 8322192

We obviously managed to create 2 different instances of this class.

The fact that these instances have shared attributes doesn't make this class a singleton.

DeepSpace
  • 65,330
  • 8
  • 79
  • 117
  • singleton means that the resources should be shared, there should not be any multiple instances of resources like logger or printer ? – deepak Jun 21 '16 at 12:07
  • Two instances aren't forced to share resources, though. After creation, you can create and assign to arbitrary attributes on each instance independently. `a = my_singleton_class(); b = my_singleton_class(); a.foo = "bar"; b.x = 3`. – chepner Jun 21 '16 at 12:15
  • @DeepSpace Depending on your implementation, the two anonymous instances you create *might* have the same id, since the second can reuse the memory previously occupied by the first. – chepner Jun 21 '16 at 12:16
1

Thechnically, your example is not a singleton. A singleton is a unique instance of a class that will be accessed throughout the whole application. In Python a singleton class is a class that can only build one single instance.

But your class can be used as a singleton because you will directly use the class itself instead of using a singleton object.

logger = my_singleton_class.logger()

It is allowed per language and I can see no immediate or serious caveat. So IMHO whether it is pythonic or nor is rather a matter of taste.

Serge Ballesta
  • 121,548
  • 10
  • 94
  • 199