So here is the code
tmp_dict = {}
x = tmp_dict.setdefault("key1", set())
x |= {1,2}
tmp_dict
And the output is
{'key1': {1, 2}}
But if we change the 3rd line to
x = x | {1,2}
then the output would be
{'key1': set()}
So I am curious why |= does such magic here that the dictionary gets updated. I thought x = x | {1,2} and x |= {1,2} would be equivalent but actually they are not.
CodePudding user response:
It's because |= references __ior__, but | references __or__.
|= will modify the original x object, which would effect the tmp_dict, but modifying x = .. would override x completely so that the reference to tmp_dict would be gone.
It would just create a variable named x with the union of the sets.
