vendredi 14 août 2020

Using global to create a singleton object in python resulting in multiple initialization

I am facing a problem where the global variable within my module keeps on getting intialized multiple times when the produce() is called. The module is imported just once but I am still unable to understand why the global variable within the module will become None.

Am I taking the right approach? Looking to make it work in python 2.7 and upwards.

producer_instance = None

def produce(message):
    producer = get_producer()
    producer.produce(message)

def get_producer():
    global producer_instance
    if producer_instance is None:        
        producer_instance = Producer()
    return producer_instance

Aucun commentaire:

Enregistrer un commentaire