r/backtickbot • • Jul 22 '21

https://np.reddit.com/r/Python/comments/opb7hm/do_not_use_mutable_objects_as_default_arguments/h65kzby/

Here's an easy code snippet (untested, but based on my experience) that should repro the problem:

class Foo:
    def __init__(self, items = []):
        self.items = items

foo = Foo()
foo.items.append("bar")
print(foo.items) # should see a list containing bar

foo2 = Foo()
print(foo.items) # you'd expect an empty list, but you'll see bar again

To avoid the problem, you can do something like this instead:

class Foo:
    def __init__(self, items = None):
        self.items = items or []

foo = Foo()
foo.items.append("bar")
print(foo.items) # should see a list containing bar

foo2 = Foo()
print(foo.items) # you should see an empty list this time
1 Upvotes

0 comments sorted by