1

I'm aware that using an empty list (or any other mutable type) as a default parameter is not a good idea, as it is described here: Why is the empty dictionary a dangerous default value in Python?.

I'm writing a class that is going to have a rather large amount of keyword arguments and that's why I have switched to **kwargs arguments (Class with too many parameters: better design strategy?).

My class looks like this:

class Scale:
    fifth_tuning = {"perfect":3/2, "meantone":5**(1/4), "equal":(2**7)**(1/12)}

    def __init__(self, **kwargs):
        scale_defaults = {
            "stack_span": 7,
            "stack_interval": self.fifth_tuning["perfect"],
            "base_frequency": 261.626,
            "base_position": 0,
            "omit_positions": list()
        }

        for (key, default_value) in scale_defaults.items():
            setattr(self, "_"+key, kwargs.get(key, default_value))

        self._freqarray = []

        self._generate_freqarray()

Now i'm not sure if I'm avoiding the danger of a mutable default argument by using a default dictionary and defining a new empty list in there or if there could be potentially dangerous consequences with this approach. Can anybody confirm that what I'm doing is safe and if it isn't why that is?

  • You *don't* have a mutable default parameter, so it's unclear why you think there might be a problem. A new scale_defaults is created for every instance and the value from fifth_tuning is immutable; there's no sharing of state. Note you could also write them separately with None for defaults that shouldn't be in the parameter list: `def __init__(self, stack_span=7, ..., omit_positions=None):`. – jonrsharpe May 17 '20 at 11:03
  • 1
    Yes, you are right, thanks! Since my dict is created every time i enter the function, obviously there isn't a problem... – RaphaelMaschinsen May 17 '20 at 11:44

0 Answers0