What tricks do you use to avoid the spontaneous python syntax?

I am an experienced programmer, but still a little green in python. I just got into an indent error that cost me a significant amount of debugging time. I was wondering what experienced python programmers do to not create such problems at all.

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 the value "value = None" has to be allocated one level. Be that as it may, the variable gets clobbered every time the unselect method is called, and not just once. I looked at it many times, not seeing what was wrong.

+4
source share
3 answers

Place all class attributes (e.g. value ) at the top, directly below the class Wizvar (below the line of the document, but above all the method definitions). If you always put class attributes in the same place, you cannot often encounter this particular error.

Please note: if you follow the above convention and wrote:

 class Wizvar(): value = None def select(self): self.selected = True def unselect(self): self.selected = False 

then Python would raise an IndentationError:

 % test.py File "/home/unutbu/pybin/test.py", line 7 def select(self): ^ IndentationError: unindent does not match any outer indentation level 
+8
source

In general: a lot of unit testing. Code reviews also help a lot.

This particular error seems easy to identify, since if value supposed to be exceeded as soon as it was a class variable, then proper unit testing would show that it is not.

Tools like PyDev do a good job of finding other common errors, so you might want to consider them.

+1
source

I have no such problems;) At least I have them less often than extra, missing or shifted brackets or classics:

 if (foo) bar(); baz(); 

in a language that uses braces.

It is said that some coding styles help. For example, I always list class variables at the top of the class body, so if I accidentally indent, I get an IndentationError instead of creating an unused local variable. By the way, I always saw it like that. Constant indentation (I'm with PEP 8 and use 4 spaces) also helps, some people use only one space for some blocks - this is very easy to overlook.

Analysis of static code (e.g. PyLint) may indicate such errors, but I do not have much experience with them. As I wrote, it just works most of the time.

+1
source

All Articles