Featured Post

Introduction to Python Tales

Hello my friends, my name is Nelson Carrasquel, and perhaps as you I have the philosophy of coding for life, since 2013 when I started programming with Python (I have started before in 2008 with Delphi and some Visual Basic, but that is my dark past) my value as a Developer really increased due to the things that I found that could be possible with Python, now Python (with some Javascript) are the core languages for almost every challenge that I face in the programming world. I am a Chemical Engineer graduated from the UCV (Central University of Venezuela) in 2015, was working as an engineer for almost two years for an Automation and Control Systems Company, programming with LabVIEW almost all the time, but also I was tutoring as a part time job, helping students from all around the world (Not all the world but all the America) in their Python and Javascript assignments and projects; I found out that I really enjoy teaching and tutoring programming languages, and from that on I was kin…

Singleton - Design Patterns in Python

Hello my friends, here in this quickly entry we are going to talk about the most basic but very useful Design Pattern and that is the Singleton, but first let's discuss as always a little about theory.

Design Patterns

This is the next step in the programing learning curve, after Object Oriented Programming there is a list of topics that you could learn next, I strongly recommend Python Design Patterns. Accordingly to the Wikipedia, “a software design pattern is a general reusable solution to a commonly occurring problem within a given context in software design”, in other words is the same code to the same kind of problems; in general we tend to find the same kind of problems when we are designing our software, and we tend to solve this problems with the same solution, in time and each time this solution is improved and finally is considered a standard or a pattern in software design, so it becomes a design pattern.



Singleton

Is a design pattern in which we can have a specified class that behaves as a global variable, by forcing that each instantiation of the class will return the same and only one object, if there was no other instance before it creates a new one, from this point in every new instance will return the reference of the very first instance created.
Before we jump into the singleton code, let's talk about the problem that we find singleton suitable as a solution.

The Problem

When we are designing very large applications with Python we tend to do some separation of concerns using modules and submodules, organizing them into directories and subdirectories, and sometimes we need to import some resources from another module in another directory and this can become really hard to code, and not only the problem finish here, because also we need to have a kind global variable for holding some persistent data in memory while the program is executed, and we want to access to this data from any module; in this problem the singleton comes in very handy because we can solve this problem by using one and only one object to hold this data and access to it from any part of our application.
For example, if we are coding a web application, separation of concerns is a strong practice when an applications starts to scale up, making the code maintainable in time, and if your web application has users capability you will require an interface for the database just to handle users. Let's code a little on how would be a very basic users manager interface class.
class UserDBManager(object):

    def __init__(self):

        pass

    def create_user(self, user):

        """
        :param user: User Instance
        :return: Status Code
        """

        pass

    def update_user(self, user):

        """
        :param user: User Instance
        :return: Status Code
        """

        pass

    def user_exists(self, username):

        """
        :param username: Username String
        :return: True if user exists False otherwise
        """

        pass

    def check_email(self, email):

        """
        :param email: String
        :return: True if user exists False otherwise
        """

        pass

    def get_user(self, username):

        """
        :param username: Username String
        :return: User Instance from database
        """

        pass
   
    def get_users(self):

        """
        :return: a list of User Instances of all users in database
        """

        pass

    def verify_user(selfverify_key):

        """
        :param verify_key: String key for user verification
        :return: None
        """

        pass

This is a simple class in which all the methods make an action to the database, the body code of all of the method has been replaced with pass keyword, just for the purpose of explaining singleton and not database access, but the docstrings kind of explain what each method does.
This is a handy class because we can abstract then the manipulation of the database from our web application backend, but how do we make this in such a way that we can use it from any module and persist its own state, and that is when the code that makes this a singleton takes place; All we need to do is to place this code right before the __init__ method.
def __new__(cls):

        if not hasattr(cls'instance'):
            cls.instance = super(UserDBManagercls).__new__(cls)

        return cls.instance

The __new__ method is a class method and is the one that is executed when a new instance is created, as you can see it checks whether an instance is already created, if so will create a new one otherwise will return the one already created.
In this way we can convert a simple class into a singleton, we dump any data into it and get access to it from any module, any place in our application or software.
We have come to the end of this entry; in future entries we are going to talk about more complex design patterns, one step at a time my friends, well I hope you have found this entry helpful to you. So thanks for coming by my new entry and I hope you have enjoyed this as much as I enjoyed writing it, stop by the comments if you want to discuss about this, share in your social media and subscribe. Cheers my friends.