I have a Python set consisting of several values and I want to use method chaining like this:
>>> f = {1, 2, 3}
>>> g = f.copy().discard(3)
>>> g
>>>
but g becomes empty. However, it works without chaining:
>>> g = f.copy()
>>> g
{1, 2, 3}
>>> g.discard(3)
>>> g
{1, 2}
Can somebody explain me this behaviour?
discard()
discards an element in the set and returns None
.
so when you assign
g = f.copy().discard(3)
this is equivalent to
h = f.copy() # now h = f
g = h.discard(3) # g = None; h = {1,2}
which leaves you with g = None
.
When you do g = f.copy().discard(3)
, you are storing in g the return value of the method "discard(3)". In this case, it returns nothing, but alters the object. This is why on the second scenario it works.
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