Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What tricks do you use to avoid being tripped up by python whitespace syntax?

Tags:

python

syntax

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.

like image 445
Neil Baylis Avatar asked Dec 28 '22 08:12

Neil Baylis


1 Answers

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
like image 106
unutbu Avatar answered Feb 02 '23 00:02

unutbu