How do I fix PyDev "Method should have self as first parameter" errors

Chris B. picture Chris B. · Jan 21, 2010 · Viewed 21.4k times · Source

I'm developing in Python using PyDev in Eclipse, and some of my code generates errors in the code analysis tool. Specifically:

class Group(object):
    def key(self, k):
        class Subkey(object):
            def __enter__(s):
                self._settings.beginGroup(k)
                return self

            def __exit__(s, type, value, tb):
                self._settings.endGroup()

         return Subkey()

Gives me a "Method '__enter__- group' should have self as first parameter" error, and a similar error for __exit__. Is there a way to solve this without assigning self to another variable and reusing the variable in the other method signatures?

Answer

FogleBird picture FogleBird · Jan 21, 2010

You could disable that error in the preferences...

Window > Preferences > Pydev > Editor > Code Analysis > Others

Or refactor the code...

class Group(object):
    def key(self, k):
        outer_self = self
        class Subkey(object):
            def __enter__(self):
                outer_self._settings.beginGroup(k)
                return outer_self

            def __exit__(self, type, value, tb):
                outer_self._settings.endGroup()

         return Subkey()

What else do you expect? The error checks are there to help you. If you don't think they're legitimate errors, disable them or refactor the code.

In this case I'd say refactor the code. It's more readable, as evidenced by King Radical's answer. He didn't understand that s was another self.