Should I use a global variable or is there any other option in this example?

51 Views Asked by At

I have a question regarding the use of global variable. I have a situation something like this: I have to loop through forest and then through hives to find the bee and then the bee should deposit honey in honey_jar.

I could use this approach:

class HoneyJar:
    def deposit_honey(self, bee):
        print(f"Honey desposited by {bee}")


def loop_bees(nest):
    bees = [1, 2, 3, 4]  # Assume i have bees from some nest
    for bee in bees:
        honey_jar = HoneyJar()
        honey_jar.deposit_honey(bee)


def loop_hives(forest):
    bee_nests = [1, 2, 3, 4]  # Assume i have bee_nest from some forest
    for bee_nest in bee_nests:
        loop_bees(bee_nest)


def main():
    forests = ['Amazon', 'Madagascar']
    for forest in forests:
        loop_hives(forest)


main()

But that would mean I create instance of HoneyJar in every loop.

I could tackle this problem by creating the honey_jar on top level and using it as a global variable.

honey_jar = HoneyJar()

def loop_bees(nest):
    global honey_jar

    bees = [1, 2, 3, 4]  # Assume I have bees from some nest
    for bee in bees:
        honey_jar.deposit_honey(bee)

What would a better approach?

1

There are 1 best solutions below

2
Andrei I On

As Matthias suggested you should use something like this in your main.
First thing is to create a single instance of HoneyJar in the main, then pass the reference to the other methods.

def main():
    forests = ['Amazon', 'Madagascar']
    honey_jar = HoneyJar() # instantiate HoneyJar once here
    for forest in forests:
       loop_hives(forest=forest, jar=honey_jar) # then pass it to the other methods

And your loop_hives and loop_bees would be :

def loop_bees(nest, jar):
    bees = [1, 2, 3, 4]  # Assume i have bees from some nest
    for bee in bees:
        jar.deposit_honey(bee)


def loop_hives(forest, jar):
    bee_nests = [1, 2, 3, 4]  # Assume i have bee_nest from some forest
    for bee_nest in bee_nests:
        loop_bees(bee_nest, jar)