pidgey pidgey - 3 months ago 8
Python Question

Force creation of new memory object python

How do I forcefully create a new object (in this case a dictionary) in python? The following should explain my problem:

>>> class A():
... def __init__(self, a={}):
... self.a=a
...
>>> id(A().a) == id(A().a)
True

>>> class A():
... def __init__(self, a=dict()):
... self.a=a
...
>>> id(A().a) == id(A().a)
True

>>> class A():
... def __init__(self, a={}):
... self.a=copy.deepcopy(a)
...
>>> id(A().a) == id(A().a)
False


As you can see, the first two methods give me a pointer to the same empty dictionary, which means if I modify the dictionary in one object, it gets modified in the other. The third method seems so "unclean" to me. Is there an alternative? I know I could also use copy.copy, but I prefer deepcopy, for exactly these reasons.

NPE NPE
Answer

Here is a common idiom:

def __init__(self, a=None):
  if a is None:
    a = {}
  ...
Comments