-1

I have a class A

class A:
  __dict__ = {"x": 0}

  def __init__(self, **kwargs):
    self.__dict__.update(kwargs.copy())

When I create A objects:

>>> a = A(x=2)
>>> b = A(x=3)
>>> print(a.__dict__)
{x: 3}
>>> print(b.__dict__)
{x: 3}

When I preset dict without init, it becomes mutable, how can I avoid that?

Just_Me
  • 111
  • 8

1 Answers1

0

you can use dict.copy() to get a new (shallow!) copy of kwargs, like this:

class A:
  def __init__(self, **kwargs):
    self.local_copy = kwargs.copy()
    print(id(self.local_copy))

a2 = A(x=2)
a3 = A(x=3)
print(a2.local_copy)
print(a3.local_copy)

example output:

15067008
15031824
{'x': 2}
{'x': 3}

EDIT:
as @chepner pointed out in the comments, the copy is unnecessary.
I assume the reason you get the same id for the 2 different invocations is that kwargs is unreferenced once the function returns, so the object may be garbage collected, and its address is reused.

even without copy, I get the same results: (2 different IDs, and distinct A objects)

Adam.Er8
  • 12,675
  • 3
  • 26
  • 38