Reputation: 384
Many articles on Internet say that python parameters are passed by reference. But from this snippet, the variable d is unchanged after the function test() is called. It is different from C/C++. Could someone please explain it? Thanks.
def test(_d : dict):
_d = dict()
_d.update({'D': 4})
print("Inside the function",_d)
return
d = {'A': 1,'B':2,'C':3}
test(d)
print("outside the function:", d) # expected: {'D:4}
Upvotes: 1
Views: 107
Reputation: 104092
Nothing complicated here.
When you have _d = dict()
you just created a new name _d
(local to the function test
) for a new dict and lost the local name _d
referring to the global dict d
that passed to that function as _d
initially:
def test(_d : dict):
print("Passed _d id:",id(_d))
_d = dict()
print("new _d id:",id(_d))
_d.update({'D': 4})
print("Inside the function",_d)
return
d = {'A': 1,'B':2,'C':3}
print('Passed d id:',id(d))
test(d)
print("outside the function:", d) # expected: {'A':1, 'B':2, 'C':3, 'D:4}
Prints:
Passed d id: 4404101632
Passed _d id: 4404101632
new _d id: 4405135680
Inside the function {'D': 4}
outside the function: {'A': 1, 'B': 2, 'C': 3}
Now try:
def test(_d : dict):
print("Passed _d id:",id(_d))
# _d = dict()
print("new _d id?:",id(_d))
_d.update({'D': 4})
print("Inside the function",_d)
return
d = {'A': 1,'B':2,'C':3}
print('Passed d id:',id(d))
test(d)
print("outside the function:", d) # expected: {'A':1, 'B':2, 'C':3, 'D:4}
Prints:
Passed d id: 4320473600
Passed _d id: 4320473600
new _d id?: 4320473600
Inside the function {'A': 1, 'B': 2, 'C': 3, 'D': 4}
outside the function: {'A': 1, 'B': 2, 'C': 3, 'D': 4}
Note in the second case the id is the same at all three places printed so it is the same object; in the first case, the id changes so you have a different object after _d = dict()
is called.
Note:
Since d
is global and mutable, this works as expected as well:
def test():
d.update({'D': 4})
d = {'A': 1,'B':2,'C':3}
test()
print(d) # {'A': 1, 'B': 2, 'C': 3, 'D': 4}
Upvotes: 1