Search code examples
pythondebuggingself

Forgetting self qualifier: how to catch this mistake?


I understand why Python requires explicit self qualifier when referring to instance attributes.

But I often forget it, since I didn't need it in C++.

The bug I introduce this way is sometimes extremely hard to catch; e.g., suppose I write

if x is not None:
    f()

instead of

if self.x is not None:
    f()

Suppose attribute x is usually None, so f() is rarely called. And suppose f() only creates a subtle side effect (e.g., a change in a numeric value, or clearing the cache, etc.). Unless I have insane amount of unit tests, this mistake is likely to remain unnoticed for a long time.

I am wondering if anyone knows coding techniques or IDE features that could help me catch or avoid this type of bug.


Solution

  • Don't name your instance attributes the same things as your globals/locals.

    If there isn't a global/local of the same name, you'll get a global "foo" is not defined error when you try to access self.foo but forget the self..

    As a corollary: give your variables descriptive names. Don't name everything x - not only does this make it far less likely you'll have variables with the same name as attributes, it also makes your code easier to read.