Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Methods don't chain in Python set

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?

like image 317
Anton Khodak Avatar asked Sep 15 '15 19:09

Anton Khodak


2 Answers

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.

like image 130
hiro protagonist Avatar answered Oct 02 '22 13:10

hiro protagonist


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.

like image 25
Rodrigo Avatar answered Oct 02 '22 14:10

Rodrigo