Search code examples
pythonglobalencapsulation

How should I use encapsulated variable in outter function in Python without global?


I am trying to write two functions: function_1 is executed inside function_2, however it is using the object var instanced inside function_2. Issue is that var is encapsulated inside function_2 and is not reachable for function_1. How can I work that out not using the global variable? New instance var must be created with every iteration of the while loop.

def function_1():
    var.method()

def function_2():
    while True:
        var = Object()
        function_1()

Solution

  • Use a function parameter:

    def function_1(parameter):
        parameter.method()
    
    def function_2():
        while True:
            var = Object()
            function_1(var)