Junior — Middle
How can the state of a global object be changed inside a function?
sobes.tech AI
Answer from AI
In Python, to modify the state of a global object inside a function, you need to use the global keyword if you want to reassign the global variable. If the global object is mutable (e.g., a list or dictionary), you can modify its contents directly without global.
Example:
counter = 0
def increment():
global counter
counter += 1
increment()
print(counter) # Outputs 1
For a mutable object:
config = {'mode': 'test'}
def set_prod_mode():
config['mode'] = 'prod'
set_prod_mode()
print(config) # {'mode': 'prod'}