Home > Enterprise >  modify a global variable from a function that is inside another function
modify a global variable from a function that is inside another function

Time:10-02

I want to modify variables "player_row" and "player_column" from the function "second_function" which is inside the function "first_function".

If I modify those variables from first_function it works, but my program requires the function "second_function" modifies those variables.

Code:

#functions
def first_function(a, b):
    second_function(a, b)
    print(f"Inside first_function: {a}, {b}")

def second_function(x, y):
    x = 5
    y = 10
    print(f"Inside second_function: {x}, {y}")


#Main
#Variables
player_row = 0
player_column = 0

first_function(player_row, player_column)
print(f"Inside MAIN: {player_row}, {player_column}")

Result:

Inside second_function: 5, 10

Inside first_function: 0, 0

Inside MAIN: 0, 0

CodePudding user response:

You can use this to change the value of variable from another function:

#functions
def first_function(a, b):
    a,b = second_function(a, b)
    print(f"Inside first_function: {a}, {b}")

def second_function(x, y):
    x = 5
    y = 10
    print(f"Inside second_function: {x}, {y}")
    return (x,y)


#Main
#Variables
player_row = 0
player_column = 0

first_function(player_row, player_column)
print(f"Inside MAIN: {player_row}, {player_column}")

You can use a similar return statement in first function as well to changethe value of variables in MAIN

CodePudding user response:

This is because Python is a "pass-by-value" language. Instead of passing a reference that you could change to refer to another value, you pass the value itself.

You have two options: one is to return a value out of your functions that represents the new state of your program, the other is to pass in a value that can be modified. (The difference this works and your original code does not is because the value will still be the same object, in that it will occupy the same memory, but you will have changed the contents of that memory)

Returning a value:

def func_1(row, col):
    return func_2(row, col)

def func_2(row, col):
    return 5, 10

row, col = func_1(0, 0)

Modifying a mutable object:

from dataclasses import dataclass

@dataclass
class Player:
    row: int = 0
    col: int = 0

def func_1(player):
    func_2(player)

def func_2(player):
    player.row = 5
    player.row = 10

player = func_1(Player())  # Player(row=5, col=10)
  • Related