Singleton Design Pattern - Advanced Python Tutorial #9

NeuralNine · Beginner ·🛠️ AI Tools & Apps ·5y ago

Key Takeaways

The Singleton design pattern in Python is demonstrated, allowing only one instance of a class to exist, and can be implemented using a private instance variable and a static method to get the instance. This pattern is useful for implementing a global point of access to a resource.

Full Transcript

[Music] what is going on guys welcome back to the advanced python tutorial series in today's video we're going to talk about the singleton design pattern so let us get right into it all right so you guys really seem to enjoy those design pattern videos so today we're going to talk about another one and uh the singleton design pattern is actually quite simple the basic idea is that we have a class and this class can only have one single instance so if we have for example a class person a normal class person we can do as many person objects as we can fit into the memory uh whereas in a singleton we can only have one person one one person object if that person would be a singleton so this is what we're going to model today we're going to again import from abc so from abstract class we're going to import abc meta and we're going to import abstract static method because we're going to work with an interface just for the sake of it uh we're going to have an interface person so i person and the mata class is going to be um it's going to be abc meta there you go and we're going to have one method in here which is going to be an abstract static method and this is going to be get data of this person and we're going to implement it in the child so implement in child class like that um and then we can have a person singleton class so we're going to say class person singleton and by the way i just want to mention here that this is not the only possible implementation you can do many different things you can use decorators you can use uh your own meta class you can have um an interface i person also a class singleton that you extend uh or inherit in the in the person class so there are many ways to go about that i think there's a stack overflow question um where one guy asked how to do a singleton design pattern in python and the top answer had like four methods so you can use all of those uh but this is just one of them or one possible way to implement a singleton design pattern in python so we're going to extend from the or inherit from the iperson interface and in here we're going to say instance with uh two double underscores uh or actually yeah with two underscores uh before the name so that it's private and we're going to say instance is none by default so this is this instance thing here this instance variable is going to be the one the single one instance that we can um create here and what we're going to do then is we're going to have a method called static method or it's going to be a static method and it's going to be called get instance so we can get the current instance or actually the only instance that there is and what we're going to do here is we're going to say if person singleton dot instance if this instance equals none now here we can do different things now this is basically the case where you're requesting the instance uh but no instance is there so we haven't created a person object yet so there's not even a single instance now here you can one way is to just say and is to say something like print error because there was no instance found or you can just create one now of course if you have some parameters uh you can you can enter some default values and then later on change them but that's up to you maybe you don't want to to allow to get an instance here because you say okay there is no instance i'm not going to return anything or you're going to return none that's also possibility in this case we're just going to create a person singleton with a default name we can choose whatever we want for that name and a default age of 0 and if the instance is not none so if it's already set if we already have an instance we're going to return the instance that we had previously so we're going to skip the if part here so this is a basic get instance and now we also need a constructor or an initializer and for this we're going to just say def init the basic initializer self name h and we're going to say self.name equals name self.h equals h and person singleton instance equals self so that this instance here gets the object self assigned um now one thing that we need to add here though is that we need to make sure that this constructor cannot be used multiple times because then we would always override the instance um and for this we're going to add a simple if statement so we're going to say if person singleton dot instance instance uh it's not none so if we already have one we're just going to do nothing i mean here again we can choose what do we want to do we can do nothing so we can just skip the constructor we can say okay there is already an object and do nothing or we can even erase an exception and say okay uh we're not just going to tell you that there already is an instance we're also going to raise an exception and create a problem for you so that you need to catch it and we can do this by just saying raise exception singleton cannot be instantiated instantiated more than once like that and otherwise we're just going to do oh sorry we're just going to come on there you go um otherwise we're just going to create to assign the values and to assign the self object to the instance so this is the basic way in which we create an object and then we're also going to have to implement the extra abstract method which is get data and in this case this is quite simple we're just going to since it's a static method we need to add the annotation here we're just going to get the data from the instance so we can say something like um actually did we call it get data let's rename it to print data because get is most of the time a return thing and print is printing obviously so we're going to call it print data and then we're going to just print a formatted string in which we say name is person singleton instance name like that and then we're going to do the same thing for the h so we're going to say h is person singleton dot instance dot h so that's it um and then what we can do now is we can create uh or we can try to create more than one object and we're going to see what happens but first of all let's do it in a proper way here so let's just go ahead and say i don't know p equals person singleton and let's add the name mike and mike is 30 years old and then we can go ahead and say p dot print data and we can also go ahead and print p as an object this is going to be important for later on now let's see if we have any errors doesn't seem like that or we have one okay we need to return the person person singleton dot instance that should be it yes so then we can open up a terminal here terminal split dash and uh we can navigate to the i hope i'm not blocking by the way with the camera i bet i'm blocking everything again so let me just resize this here uh let me go through the code again so that you guys don't have to complain in the comment section so this is the code there you go and now actually let's go ahead and open this in a new tab here so let's say terminal tab bash and now we're going to navigate to this directory and we're going to say python3 main.py and you can see we have this person singleton object with the values and now if i go ahead and try to create a second one so if i say something like p2 equals person singleton person singleton uh i don't know bob and bob is going to be 25 this is going to fail so we can see that this is going to fail if we try you can see that we get the exception singleton cannot be instantiated more than once however i can of course go ahead and say something like p2 equals person singleton dot get instance so that we can save it in a second variable and a second reference here and if i do that actually let's add to those two things so we're going to copy that here and we're going to change this to p2 and this to p2 as well and then we're going to see that this is actually the same thing so you can see we have not only the same values we have the exact same address because of course we have just one instance uh we cannot create a second one because that's not possible and even if we were to ignore it we would always uh so even if we don't raise an exception here um at this point we can just ignore it but not overwrite the instance or even if we overwrite it we would just have a new instance but it's only going to be one instance uh at the same time we're not going to have multiple instances here so that's it for this video hope you enjoyed i hope you learned something if so let me know by hitting the like button and leaving a comment in the comment section down below and of course don't forget to subscribe to this channel and hit the notification bell to not miss a single future video for free other than that thank you very much for watching see you next video and [Music] bye [Music] you

Original Description

In this video we talk about the singleton design pattern in Python. ◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾ 📚 Programming Books & Merch 📚 💻 The Algorithm Bible Book: https://www.neuralnine.com/books/ 🐍 The Python Bible Book: https://www.neuralnine.com/books/ 👕 Programming Merch: https://www.neuralnine.com/shop 💻 Exclusive Content 💻 👥 Patreon: https://www.patreon.com/neuralnine 🌐 Social Media & Contact 🌐 📱 Website: https://www.neuralnine.com/ 📷 Instagram: https://www.instagram.com/neuralnine 🐦 Twitter: https://twitter.com/neuralnine 🤵 LinkedIn: https://www.linkedin.com/company/neuralnine/ 📁 GitHub: https://github.com/NeuralNine 🎵 Outro Music From: https://www.bensound.com/
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from NeuralNine · NeuralNine · 0 of 60

← Previous Next →
1 Visualizing Stock Data With Candlestick Charts in Python
Visualizing Stock Data With Candlestick Charts in Python
NeuralNine
2 Python Beginner Tutorial #1 - Installation and First Program
Python Beginner Tutorial #1 - Installation and First Program
NeuralNine
3 Python Beginner Tutorial #2 - Variables and Data Types
Python Beginner Tutorial #2 - Variables and Data Types
NeuralNine
4 Python Beginner Tutorial #3 - Operators and User Input
Python Beginner Tutorial #3 - Operators and User Input
NeuralNine
5 Python Beginner Tutorial #4 - If Statements and Conditions
Python Beginner Tutorial #4 - If Statements and Conditions
NeuralNine
6 Python Beginner Tutorial #5 - Loops
Python Beginner Tutorial #5 - Loops
NeuralNine
7 Python Beginner Tutorial #6 - Sequences and Collections
Python Beginner Tutorial #6 - Sequences and Collections
NeuralNine
8 Python Beginner Tutorial #7 - Functions
Python Beginner Tutorial #7 - Functions
NeuralNine
9 Python Beginner Tutorial #8 - Exception Handling
Python Beginner Tutorial #8 - Exception Handling
NeuralNine
10 Python Beginner Tutorial #9 - File Operations
Python Beginner Tutorial #9 - File Operations
NeuralNine
11 Python Beginner Tutorial #10 - String Functions
Python Beginner Tutorial #10 - String Functions
NeuralNine
12 Python Intermediate Tutorial #1 - Classes and Objects
Python Intermediate Tutorial #1 - Classes and Objects
NeuralNine
13 Python Intermediate Tutorial #2 - Inheritance
Python Intermediate Tutorial #2 - Inheritance
NeuralNine
14 Python Intermediate Tutorial #3 - Multithreading
Python Intermediate Tutorial #3 - Multithreading
NeuralNine
15 Python Intermediate Tutorial #4 - Synchronizing Threads
Python Intermediate Tutorial #4 - Synchronizing Threads
NeuralNine
16 Python Intermediate Tutorial #5 - Events and Daemon Threads
Python Intermediate Tutorial #5 - Events and Daemon Threads
NeuralNine
17 Python Intermediate Tutorial #6 - Queues
Python Intermediate Tutorial #6 - Queues
NeuralNine
18 Python Intermediate Tutorial #7 - Sockets and Network Programming
Python Intermediate Tutorial #7 - Sockets and Network Programming
NeuralNine
19 Python Intermediate Tutorial #8 - Database Programming
Python Intermediate Tutorial #8 - Database Programming
NeuralNine
20 Python Intermediate Tutorial #9 - Recursion
Python Intermediate Tutorial #9 - Recursion
NeuralNine
21 Python Intermediate Tutorial #10 - XML Processing
Python Intermediate Tutorial #10 - XML Processing
NeuralNine
22 Python Intermediate Tutorial #11 - Logging
Python Intermediate Tutorial #11 - Logging
NeuralNine
23 Python Data Science Tutorial #1 - Anaconda and PyCharm Setup
Python Data Science Tutorial #1 - Anaconda and PyCharm Setup
NeuralNine
24 Python Data Science Tutorial #2 - NumPy Arrays
Python Data Science Tutorial #2 - NumPy Arrays
NeuralNine
25 Python Data Science Tutorial #3 - Numpy Functions
Python Data Science Tutorial #3 - Numpy Functions
NeuralNine
26 Python Data Science Tutorial #4 - Plotting Functions With Matplotlib
Python Data Science Tutorial #4 - Plotting Functions With Matplotlib
NeuralNine
27 Python Data Science Tutorial #5 - Subplots and Multiple Windows
Python Data Science Tutorial #5 - Subplots and Multiple Windows
NeuralNine
28 Python Data Science Tutorial #6 - Matplotlib Styling
Python Data Science Tutorial #6 - Matplotlib Styling
NeuralNine
29 Python Data Science Tutorial #7 - Bar Charts with Matplotlib
Python Data Science Tutorial #7 - Bar Charts with Matplotlib
NeuralNine
30 Python Data Science Tutorial #8 - Pie Charts with Matplotlib
Python Data Science Tutorial #8 - Pie Charts with Matplotlib
NeuralNine
31 Python Data Science Tutorial #9 - Plotting Histograms with Matplotlib
Python Data Science Tutorial #9 - Plotting Histograms with Matplotlib
NeuralNine
32 Python Data Science Tutorial #10 - Scatter Plots with Matplotlib
Python Data Science Tutorial #10 - Scatter Plots with Matplotlib
NeuralNine
33 Python Data Science Tutorial #11 - 3D Plotting with Matplotlib
Python Data Science Tutorial #11 - 3D Plotting with Matplotlib
NeuralNine
34 Python Data Science Tutorial #12 - Pandas Series
Python Data Science Tutorial #12 - Pandas Series
NeuralNine
35 Python Data Science Tutorial #13 - Pandas Data Frames
Python Data Science Tutorial #13 - Pandas Data Frames
NeuralNine
36 Python Data Science Tutorial #14 - Pandas Statistics
Python Data Science Tutorial #14 - Pandas Statistics
NeuralNine
37 Python Data Science Tutorial #15 - Pandas Sorting and Functions
Python Data Science Tutorial #15 - Pandas Sorting and Functions
NeuralNine
38 Python Data Science Tutorial #16 - Pandas Merging Data Frames
Python Data Science Tutorial #16 - Pandas Merging Data Frames
NeuralNine
39 Python Data Science Tutorial #17 - Pandas Queries
Python Data Science Tutorial #17 - Pandas Queries
NeuralNine
40 Python Machine Learning Tutorial #1 - What is Machine Learning?
Python Machine Learning Tutorial #1 - What is Machine Learning?
NeuralNine
41 Python Machine Learning Tutorial #2 - Linear Regression
Python Machine Learning Tutorial #2 - Linear Regression
NeuralNine
42 Python Machine Learning Tutorial #3 - K-Nearest Neighbors Classification
Python Machine Learning Tutorial #3 - K-Nearest Neighbors Classification
NeuralNine
43 Python Machine Learning #4 - Support Vector Machines
Python Machine Learning #4 - Support Vector Machines
NeuralNine
44 Python Machine Learning Tutorial #5 - Decision Trees and Random Forest Classification
Python Machine Learning Tutorial #5 - Decision Trees and Random Forest Classification
NeuralNine
45 Python Machine Learning Tutorial #6 - K-Means Clustering
Python Machine Learning Tutorial #6 - K-Means Clustering
NeuralNine
46 Python Machine Learning Tutorial #7 - Neural Networks
Python Machine Learning Tutorial #7 - Neural Networks
NeuralNine
47 Python Machine Learning Tutorial #8 - Handwritten Digit Recognition with Tensorflow
Python Machine Learning Tutorial #8 - Handwritten Digit Recognition with Tensorflow
NeuralNine
48 Generating Poetic Texts with Recurrent Neural Networks in Python
Generating Poetic Texts with Recurrent Neural Networks in Python
NeuralNine
49 Stock Portfolio Visualization with Matplotlib in Python
Stock Portfolio Visualization with Matplotlib in Python
NeuralNine
50 Analyzing Coronavirus with Python (COVID-19)
Analyzing Coronavirus with Python (COVID-19)
NeuralNine
51 Making Text Images Readable Again with Python and OpenCV
Making Text Images Readable Again with Python and OpenCV
NeuralNine
52 Neural Networks Simply Explained (Theory)
Neural Networks Simply Explained (Theory)
NeuralNine
53 Motion Filtering with OpenCV in Python
Motion Filtering with OpenCV in Python
NeuralNine
54 Top 5 Programming Languages To Learn in 2020
Top 5 Programming Languages To Learn in 2020
NeuralNine
55 Simple TCP Chat Room in Python
Simple TCP Chat Room in Python
NeuralNine
56 Image Classification with Neural Networks in Python
Image Classification with Neural Networks in Python
NeuralNine
57 Edge Detection with OpenCV in Python
Edge Detection with OpenCV in Python
NeuralNine
58 S&P 500 Web Scraping with Python
S&P 500 Web Scraping with Python
NeuralNine
59 Simple Sentiment Text Analysis in Python
Simple Sentiment Text Analysis in Python
NeuralNine
60 Introduction - Algorithms & Data Structures #1
Introduction - Algorithms & Data Structures #1
NeuralNine

This video teaches the Singleton design pattern in Python, which allows only one instance of a class to exist. It is useful for implementing a global point of access to a resource. By following the steps in this video, you can implement the Singleton design pattern in your own Python projects.

Key Takeaways
  1. Create a private instance variable to hold the single instance of the class
  2. Implement a static method to get the instance of the class
  3. Use the static method to get the instance of the class
  4. Implement a constructor to initialize the instance
  5. Try to create a second instance of the class
  6. Get the instance using a static method
  7. Compare the values and addresses of the instances
💡 The Singleton design pattern ensures that only one instance of a class is created, and provides a global point of access to that instance.

Related Reads

📰
Stop Copy-Pasting: How to Use an AI Content Copilot to Rewrite Your Resume Bullet Points
Learn to use AI content copilots to rewrite resume bullet points and tailor your resume for each job application
Medium · AI
📰
5 AI Apps in 2026 That Can Actually Help You Start a Side Hustle
Discover 5 AI-powered apps that can help you start a side hustle in 2026, from automating tasks to generating new business ideas
Medium · Data Science
📰
The AI Tools You’re Paying For Have Free Twins Nobody Mentions
Many AI tools have free alternatives with similar functionality, learn how to identify and utilize them to optimize your budget
Medium · AI
📰
8 Free Web Tools I Built With AI — No Uploads, No Sign-ups, All Browser-Based
Explore 8 free AI-powered web tools that run locally in your browser, requiring no uploads or sign-ups, and learn how to utilize them for various tasks
Dev.to · gan liu
Up next
How AI Is Transforming Analytics in Tableau Cloud & Server
Salesforce Product Center
Watch →