简体   繁体   中英

Why can |= do in-place value update for dictionaries in Python?

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} 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} x = x | {1,2} and x |= {1,2} would be equivalent but actually they are not.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM