S. A.
S. A.

Reputation: 111

Pylint says: W0233: __init__ method from a non direct base class 'Nested' is called (non-parent-init-called)

I'm newbie in programming and python also. When I try to wrap my data structure to class in order not to make list or dict iterating, I get the pylint error message:

W0233: __init__ method from a non direct base class 'Nested' is called (non-parent-init-called)

Is there any best "pythonic" way to do this?

My json data is so:

{
    "template"  :   [
        {
            "folder"    :   "/Users/SA/Documents/GIT/rs-finance/templates",
            "basetpl"   :   "tpl.docx",
            "header"    :   "header_tpl.docx",
            "table"     :   "table_tpl.docx", 
            "footer"    :   "footer_tpl.docx"
        }
    ],
    "export"    :   [
        {
            "folder"    :   "/Users/SA/Documents/GIT/rs-finance/export",
            "name"      :   "result.docx"
        }
    ]
}

And when I load this data (or its piece) to dict or list variable & try to wrap it with this class:

class Nested ():
    def __init__(self, data):
        if isinstance (data, dict):
            for key, value in data.items():
                if isinstance(value, (float, int, str)):
                    setattr(self, key, value)
                else:
                    setattr(self, key, Nested(value))
        if isinstance(data, list):
            for item in data:
                self.__init__(item)

The Pylint doesn't like my last line 😳

Upvotes: 2

Views: 1060

Answers (1)

chepner
chepner

Reputation: 531325

Calling __init__ explicitly isn't wrong, but it is odd, and that's all Pylint is warning you about.

A better practice is to write a separate recursive function that does what you want, then call that from __init__.

class Nested:
    def __init__(self, data):
        self.recursive(data)

    def recursive(self, data):
        if isinstance(data, dict):
            for key, value in data.items():
                if isinstance(value, (float, int, str)):
                    setattr(self, key, value)
                else:
                    setattr(self, key, Nested(value))
        elif isinstance(data, list):
            for item in data:
                self.recursive(item)

Upvotes: 3

Related Questions