I have a class with a member that is defined:
self.myset = set()
When I perform myobject.myset.add('item'), using an instance of my class, it works fine: print(myobject.myset) gives me {'item'} .
However, when I perform myobject.myset.union(yourset), where yourset is not empty, it won't work; print(myobject.myset) still prints as an empty set. Why is one method (add) working while another (union) is quietly (no exception thrown) failing? Even myobject.myset = yourset works, but union in particular won't.
I'm using Python 3.
set.union() does not modify the old set in-place, but set.add() does. set.union() returns a new set instead.
myobject.myset = myobject.myset.union(yourset)
This should do the trick. See the Python documentation on set.union() for more information.
union doesn't modify the set - it returns a new set. This is clearer if you use the operators for union and intersection - a.union(b) and a | b do the same thing (except that the method form can take the union of three or more sets without creating extra temporary objects). For an in place union, you can use the update method or the equivalent (for two sets) form a |= b.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With