Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22910

Python Morsels: Making a singleton in Python

$
0
0

While it is possible to make singleton objects in Python, the classic singleton design pattern doesn't always make a lot of sense.

What is a singleton?

A singleton class is a class that only allows creating one instance of itself.

None is an example of a singleton object in Python. The class of None is NoneType:

>>> type(None)<class 'NoneType'>

If we try to call the NoneType class, we'll get back an instance of that class.

>>> new_none=type(None)()

But every instance of the NoneType class is identical to every other instance of the NoneType class:

>>> new_noneisNoneTrue

So there's only one instance of NoneType in Python, and it's None.

Making a singletons in Python with a custom constructor

Here we have a class …

Read the full article: https://www.pythonmorsels.com/making-singletons/


Viewing all articles
Browse latest Browse all 22910

Trending Articles