A dictionary that I pass as an argument seems to behave like a global variable. This was a surprise to me but it seems that it makes sense in Python (see for instance this topic). However, I'm very surprised that I get a different behavior for a different type of variable. Let assume that I have a script main.py that calls two functions from a module.
import mymodule
an_int = 42
a_dict = {'value':42}
mymodule.print_and_reassign(a_dict, an_int)
mymodule.print_again(a_dict, an_int)
with my modules.py containing the following functions
def print_and_reassign(a_dict, an_int):
# Dictionary
print(f"Dictionary value: {a_dict['value']}")
a_dict['value']=970
# Integer
print(f"Integer value: {an_int}")
an_int=970
def print_again(a_dict, an_int):
# Dictionary
print(f"Dictionary value: {a_dict['value']}")
# Integer
print(f"Integer value: {an_int}")
By running main.py, I get the following results
Dictionnary value: 42
Integer value: 42
Dictionnary value: 970
Integer value: 42
This is very counterintuitive to me. Why does the dictionary changed while the integer remains unchanged?
source https://stackoverflow.com/questions/73547620/dictionary-behaves-like-a-global-variable
Comments
Post a Comment