Sobes.tech
Middle

How can you limit the visibility of a global variable between two functions in Python?

sobes.tech AI

Answer from AI

Using scope and functions as first-class objects. You can pass a variable as an argument or use closures.

Example of passing an argument:

def function1(variable):
    # Using variable
    print(f"function1: {variable}")

def function2(variable):
    # Using variable
    print(f"function2: {variable}")

# Passing the variable to each function
my_variable = "Hello"
function1(my_variable)
function2(my_variable)

Example of using a closure:

def outer_function():
    # Local variable accessible only to functions inside outer_function
    scoped_variable = "Scoped!"

    def inner_function1():
        # Access to scoped_variable via closure
        print(f"inner_function1: {scoped_variable}")

    def inner_function2():
        # Access to scoped_variable via closure
        print(f"inner_function2: {scoped_variable}")

    return inner_function1, inner_function2

# Getting functions that "remember" scoped_variable
func1, func2 = outer_function()

# Calling functions, variable is visible only to them
func1()
func2()