Wednesday, December 25, 2013

python + pylint + sublime text = pylinton

I write Python with Notepad++ or Geany, and got sick of getting NameErrors which could have been foreseen. The simplest example is

#foo.py
def foo():
    print x
foo()

But imagine something more nasty happening because of your own stupidity which pops out in a function that's been running for a good hour's time.

So, yeah, tests and everything... But can't there be a way to pay a bit less for such a stupid error?

Introducing: pylint. Like jslint which I've already met, pylint checks your Python code for stupid mistakes such as this. You can get it here: http://www.pylint.org/ or using pip install pylint.

You can test your pylint installation using the example from above: pylint -E foo.py will output only the most important errors, and will of course exit with a nonzero status code.

Nice! But how would I add this to my editors?

Introducing(2): Sublime Text. Word on the street (or on the train back home with Micky who told me about it) is that it's the coolest new lightweight editor. We don't want to write Python on Eclipse and PyDev, now, do we...?

You can get it here: http://www.sublimetext.com

Now apparently Sublime Text can build your code using all sorts of builders, including predefined! While the language for defining such builds is not very sophisticated (i.e. no conditionals), you can write a little bash script to go with it so that whenever you build your code, first pylint will go over it and won't let it run if it's buggy.

Say you put the following code in /home/you/pylinton :

#!/bin/bash
pylint -E $1 2>/dev/null
if [ $? -eq 0 ]
 then
   python $1
fi

Then, from Sublime Text, go to Tools >> Build System >> New Build System and use this definition:
{
"cmd": ["/home/you/pylinton" , "$file"]
}

Then voila! Ctrl+B builds your currently open Python source code. You'll get pylint's errors if there are any; otherwise, Python will execute. That won't replace your tests but it can save you some time and heartaches when you're running ahead.


tl;dr
(1/4) pylint is jslint for Python. http://www.pylint.org/ or using pip install pylint

(2/4) sublime editor is your new cross-platform notepad++ . http://www.sublimetext.com

(3/4) Put this in /home/you/pylinton...
#!/bin/bash
pylint -E $1 2>/dev/null
if [ $? -eq 0 ]
 then
   python $1
fi

(4/4) ...and use this as a new build system definition in sublime text:
{
"cmd": ["/home/guyrap/pylinton" , "$file"]
}



That was a bit long as well imho!!!