I'm an experienced programmer, but still a little green at python. I just got caught by an error in indentation, which cost me a significant amount of debugging time. I was wondering what experienced python programmers do to avoid creating such problems in the first place.
Here's the code (Part of a much larger program) :
class Wizvar():
def select(self):
self.selected = True
def unselect(self):
self.selected = False
value = None
The problem is that 'value = None' should be outdented one level. As it is, the variable gets clobbered every time the unselect method is called, rather than once only. I stared at this many times without seeing what was wrong.
Put all the class attributes (e.g. value
) up at the top, right under the class Wizvar
declaration (below the doc string, but above all method definitions). If you always place class attributes in the same place, you may not run into this particular error as often.
Notice that if you follow the above convention and had written:
class Wizvar():
value = None
def select(self):
self.selected = True
def unselect(self):
self.selected = False
then Python would have raised an IndentationError:
% test.py
File "/home/unutbu/pybin/test.py", line 7
def select(self):
^
IndentationError: unindent does not match any outer indentation level
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