KeyError: '_OrderedDict__root?

Hi, I have the following code snippet that gives KeyError. I checked the other links, indicating make __init__ call to Ordered Dictwhich I made. But still no luck.

from collections import OrderedDict

class BaseExcelNode(OrderedDict):
    def __init__(self):
        super(BaseExcelNode, self).__init__()
        self.start_row = -1
        self.end_row = -1
        self.col_no = -1

    def __getattr__(self, name):
        return self[name]

    def __setattr__(self, name, value):
        self[name] = value
BaseExcelNode()

Error:

Traceback (most recent call last):
  File "CIMParser.py", line 29, in <module>
    BaseExcelNode()
  File "CIMParser.py", line 9, in __init__
    super(BaseExcelNode, self).__init__()
  File "C:\Python27\lib\collections.py", line 64, in __init__
    self.__root
  File "CIMParser.py", line 15, in __getattr__
    return self[name]
KeyError: '_OrderedDict__root'
+4
source share
2 answers

Using the monkey fix method:

from collections import OrderedDict

class BaseExcelNode(OrderedDict):
    def __init__(self):
        super(BaseExcelNode, self).__init__()
        self.start_row = -1
        self.end_row = -1
        self.col_no = -1

    def __getattr__(self, name):
        if not name.startswith('_'):
            return self[name]
        super(BaseExcelNode, self).__getattr__(name)

    def __setattr__(self, name, value):
        if not name.startswith('_'):
            self[name] = value
        else:
            super(BaseExcelNode, self).__setattr__(name, value)

b = BaseExcelNode()
+1
source

OrderedDict implemented under the assumption that attribute access works by default, and in particular, this attribute access is not equivalent to indexing.

When you subclass it and change how attribute access works, you break one of the deepest implementation assumptions OrderedDictand everything goes to hell.

+2
source

Source: https://habr.com/ru/post/1654176/


All Articles