0

I am pretty new to python so it might simply be that I did not understand some parts of the language. Here is some code that I managed to make minimal for the sake of the example:

class A(object):
    def __init__(self):
        self.m = 5

class T(object):
    def __init__(self, x = []):
        self.x = x

def foo():
    t = T()
    t.x.append(A())

def bar():
    r = T()
    print(r.x)

foo()
bar()

When I run it, I get the following as a result:

python3 test.py
[<__main__.A object at 0x7f15834af4a8>]

My understanding is that a call to T() should create a T object and initialize x as an empty list. The fact that we call foo() should not influence what is happening in bar, should it?

Thank you for your help.

Kiplaki
  • 171
  • 6
  • If you don't want that to happen you need to avoid using mutable default arguments (see duplicate), e.g. use `class T(object): def __init__(self, x = None): self.x = x or []`. – MSeifert Aug 22 '17 at 16:11
  • 2
    even though this is a duplicate of an existing question, I think part of the issue is that you don't know what to search for to answer your question. This is a common python gotcha. The default argument of a list is actually persistent through all calls. You can look at this [explanation](https://docs.quantifiedcode.com/python-anti-patterns/correctness/mutable_default_value_as_argument.html) – ajoseps Aug 22 '17 at 16:13

0 Answers0