1

I extended the dictionary class to create my own and now I need to have a method which creates a new blank instance of the class and initialises it with the needed values. The problem I'm facing is that the new instance object is not a new object but just a reference to the self instance of the class.

Here the class I discussed about:

VALUES = "VALUES"
OPERATORS = "OPERATORS"

class MyDict(dict):
    def __init__(self, operators: dict = {}, values: dict = {}) -> None:
        super().__init__()
        self.set_operators_values(operators, values)

    def set_operators_values(self, operators: dict = {}, values: dict = {}):
        if not operators.keys() == values.keys():
            raise Exception("Keys of operators and values must be the same!!!")

        self[OPERATORS]: dict[str, str] = operators
        self[VALUES]: dict[str, int] = values

The strange happens when I call the following method:

def extend(self, properties: dict, data_set: DataFrame):
    column_types: dict = data_set.dtypes.to_dict()
    extended = MyDict()
    print("BLANK Extended MyDict:")
    print(extended)
    #  ...
    return extended

Here the extended object is referring to the self instance. How can I avoid this and instead create a blank new instance from within its class using a method of the object? Since I also need some data from the self object I would like to avoid creating a @staticmethod. Is there some way to do it?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
1Z10
  • 2,801
  • 7
  • 33
  • 82
  • `def set_operators_values(self, operators: dict = {}, values: dict = {}` ==> [least-astonishment-and-the-mutable-default-argument](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument) – Patrick Artner Apr 21 '19 at 07:13

1 Answers1

1

The problem comes the initialization, the instances is a new instance but the operators and values dictionaries they are referencing the same dict, this will solve it:

class MyDict(dict):
    def __init__(self, operators: dict = None, values: dict = None) -> None:
        operators = operators or {}
        values = values or {}
        super().__init__()
        self.set_operators_values(operators, values)

This is related to this famous question

Netwave
  • 40,134
  • 6
  • 50
  • 93