0

I have this python code:

class Node:
def __init__(self, label, adjacencies=[]):
    self._adjacencies = adjacencies
    self._label = label

And, somewhere later I wrote this:

def addAdjacency(self, node):
    print("adding ", node.getLabel(), " to ", self._label)
    if node in self._adjacencies:
        return
    self._adjacencies.append(node)
    node.addAdjacencies(self)

My idea is that I can do:

a = Node('a')
b = Node('b')
a.addAdjacency(b)

And that this will result in a having b and b having a in their own adjacencies list. Instead if I run:

if a.getAdjacencies() is b.getAdjacencies():
    print("BUT WHY?")

I get the string printed, and the a adjacencies list contains 'a' itself (added by b), so it seems the list is shared by the same objects, but I don't understand why, can someone explain? I found that removing the optional argument solved the issue, so it must be the problem. What am I missing?

  • Default args are defined at function definition, that is when your class is defined, so they can't be per-instance (since instances are created after class definition). – Andras Deak -- Слава Україні Mar 05 '20 at 11:09
  • The "default" value of the argument is stored *on the function object* (in the `__default__` attribute), they're not re-created per-invocation. As a result, if they are mutable previous mutations will be retained between calls. – Masklinn Mar 05 '20 at 11:09
  • 1
    Thank you! I found the question being already answered and with lot of people knowing about it. I was so astonished I had to ask it, and I didn't search good enough probably. – Vito Ruggirello Mar 05 '20 at 11:22

0 Answers0