Hi I have following code snippet which gives KeyError. I have checked other links specifying make __init__ call to Ordered Dict which I have done. 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'
                Python's OrderedDict is a dict subclass that preserves the order in which key-value pairs, commonly known as items, are inserted into the dictionary. When you iterate over an OrderedDict object, items are traversed in the original order. If you update the value of an existing key, then the order remains unchanged.
By browsing the array in order you can refer to the dictionary properly, and the order in array will survive any export in JSON, YAML, etc. Actually, you can load an OrderedDict using json. load(). There is a second parameter which tells the load method to create an OrderedDict object to keep order the same.
The Python KeyError is a type of LookupError exception and denotes that there was an issue retrieving the key you were looking for. When you see a KeyError , the semantic meaning is that the key being looked for could not be found.
Using monkey patching 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()
                        OrderedDict is implemented under the assumption that attribute access works by the default mechanisms, and in particular, that attribute access is not equivalent to indexing.
When you subclass it and change how attribute access works, you break one of the deepest assumptions of the OrderedDict implementation, and everything goes to hell.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With