0

Here I have some python code. A loop creates an object with non-binding paramerters.

The first time everything works normally.

In the second run, however, the attribute of the last object created is used as the parameter.

This works with the dictionary because it is stored in the heap.

How do I make sure that if no parameters are specified, they are not read from the heap?

class ClassXY:
    def __init__(self, variables={}):
        print(variables)
        self.variables = variables
        self.variables["key"] = "xyz"

for i in range(3):
    ClassXY()

The output:

{}
{'key': 'xyz'}
{'key': 'xyz'}

The output I want:

{}
{}
{}

Thank you :D

trincot
  • 317,000
  • 35
  • 244
  • 286
1cedsoda
  • 623
  • 4
  • 16
  • 1
    "The heap" is not a useful concept in Python. – Daniel Roseman Oct 02 '18 at 22:08
  • apparently not here – 1cedsoda Oct 02 '18 at 22:09
  • 1
    Side-note: For this particular case of the mutable default argument, a reasonable solution is to *keep* the mutable default, but change the assignment to `self.variables = variables.copy()`. Copying before storing to the instance attribute prevents mutation of the default argument, and also (partially) decouples you from any caller provided argument, so your changes don't mutate their copy of the `dict` and vice versa. And it's simpler (possibly faster) code that using `None` as the default, testing for it, and replacing `None` with a new `{}` if found. – ShadowRanger Oct 02 '18 at 22:11
  • Nice, it works fine. – 1cedsoda Oct 02 '18 at 22:17

0 Answers0