deepak
deepak

Reputation: 349

Isn't a class with class methods and attributes is singleton in python?

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 ?

Upvotes: 1

Views: 224

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 148890

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.

Upvotes: 1

DeepSpace
DeepSpace

Reputation: 81594

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.

Upvotes: 6

Related Questions