views:

50

answers:

1

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.

+6  A: 

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.

Amber
Ahh, perfect. I'm already doing everything as you said, I just didn't realize that global variables won't be defined just by referring to them! :) I should add that I just tried the assignment x = 'something'and it also was caught at compile-time:AttributeError: 'Parser' object has no attribute 'x'So everything is fine.
max