vendredi 19 mai 2023

Singleton class not shared between different modules in Python

I'm trying to implement a singleton pattern in Python to share a class between different modules. I'm experiencing some issues where the same instance is not being shared between different appearances of the singleton class.

Here is my code:

from some.module import SomeClass

class SingletonMeta(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            instance = super().__call__(*args, **kwargs)
            cls._instances[cls] = instance
        return cls._instances[cls]

class SomeClassFactory(metaclass=SingletonMeta):

    _data1 = None
    _data2 = None
    _some_class_instance = None

    @classmethod
    def get_some_class_instance(cls):
        return cls._some_class_instance

    @classmethod
    def initialize_instance(cls, data1, data2):
        if not cls._some_class_instance:
            cls._some_class_instance = SomeClass(data1, data2)
            cls._data1 = data1
           

Module 2 (some.services):

from typing import Optional, List
from some.factories import SomeClassFactory

class SomeClassService:

    def get_some_class_instance(self):
        factory = SomeClassFactory()
        return factory.get_some_class_instance()

Testing on Python Console:

from some.factories import SomeClassFactory
factory = SomeClassFactory()
factory.initialize_instance(data1, data2)
some_instance = factory.get_some_class_instance()

from some.services import SomeClassService
service_class = SomeClassService()
some_instance_2 = service_class.get_some_class_instance()  # Returns None

The expected behaviour is that some_instance and some_instance_2 would refer to the same instance of SomeClass. However, some_instance_2 is None.

Am I misunderstanding how the singleton pattern should work in Python, or is there something wrong with my implementation? Any help is greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire