Status Line in Vim

If you are following the recent trends in the Vim community you have probably noted the ever growing popularity of Powerline. As the name suggests, it is a very powerful status line generation plugin, but I don’t think that’s why most people use it. I believe its popularity has a lot to do with how sexy it looks on the bottom of your screen.

To be honest, I was never that fond of that particular extension for a variety of reasons. One of my chief gripes with it is directly related to the way it looks. Powerline uses non-standard patched fonts in order to achieve that segmented look which is not something Vim supports natively. Without them the extension looses a lot if it’s sex-appeal and starts looking a bit plain. To configure it, you don’t just add entries to your .vimrc but instead you need to create a separate dot-folder where it’s settings files are kept. While this neatly separates the Powerline setup from general Vim settings it also adds maintenance headaches. I like to keep all my Vim related config files in a single directory under source control so you can imagine this is less than optimal.

Finally, I have never really felt like I would use any of it’s advanced features. Most of the power-line setups I see on screenshots and in screen-casts are very basic: mode indcation, file path, some file and cursor position info. All of that can be easily set up in just a few lines of VimL. Powerline on the other hand is a monstrous semi-framework that can let you do really frivolous and complex things. For example, it has support for hooking into your power management module by the way of python and displaying battery status in Vim. It can also pull weather notifications from the web and display them in your status line… Though why would you ever want that is beyond me.

It is really a nice an powerful plugin, but it doesn’t seem like something I would necessarily need. For years I have been pretty happy using a very simple status line with just the name of the file and some positioning info along side the excellent Obvious-Mode plugin. It covered most of my needs – my status line would be red in insert mode, gray/cyan in normal mode, depending on whether or not the file had any unsaved changes.

Lately however I decided that I could use more informative status line. I briefly flirted with the concept of using Powerline but since I’m a system nomad who drags his .vim folder wherever he goes that idea died pretty quickly. Instead I decided to create my own status line which displays the information that I care about in a Powerline-like way but without any fancy fonts.

The killer feature for me is that I wrote it. By that I mean that if something breaks or doesn’t work correctly can easily figure out why, and fix it. Power line is pretty big and has a lot of moving parts, whereas my status line is just a dozen lines of very basic VimL so if it breaks, I can easily handle it without loosing too much time.

The result looks like this:

vim-neatstatus

Vim-NeatStatus Plugin

The mode indicator on the left changes color depending on the mode: green in normal, red in insert and blue in replace mode. I also had it turn purple in visual mode but it was kinda buggy (always lagged one keystroke behind) so at the moment it doesn’t do that. I still use Obvious-Mode so this functionality isn’t strictly necessary, but I included it so that it could be used as a stand-alone plugin.

The black box next to mode indicator shows you the server name (which in my case is treated as session name). This may not be useful to everyone, but since I set up my Vim to save sessions on exit I actually like to see that information somewhere.

To the left of the file path I have file type (ie. what language vim thinks this file is written in), file format (important if you jump between systems as much as me) and encoding (as in utf8 or not). The last may not seem fairly relevant to you, but sometimes it does matter: especially if you are trying to parse files in a certain way, or if you create a script that doesn’t run properly because the non-vim text editor decided to insert a BOM in it for shits and giggles.

Next I have the buffer number (which is useful when you have a lot of buffers open) and cursor positioning info with the current line highlighted in pink to stand out and be easily readable. There is also one more bit that is not visible in the picture above: whenever you edit a file, a little pink notification appears in the right corner of your status bar to let you know that the file has unsaved changes. Once again this is a duplication of Obvious-Mode functionality but it can be useful if you decide to install it as a stand-alone.

The colors work both in the graphical Vim as well as in the console (though you may need one that supports 256 colors). I tested it in in Gvim, MacVim and using Gnome-Console as well as Cygwin MinTTY on Windows.

I made the entire thing available as a plugin that can be easily installed via Pathogen like this:

cd ~/.vim/bundle
git clone git://github.com/maciakl/vim-neatstatus.git

If you have your .vim under source control like me then do:

cd ~/.vim
git submodule add git://github.com/maciakl/vim-neatstatus.git bundle/vim-neatstatus
git submodule init
git submodule update

At the moment the colors are hard coded and the plugin is not very configurable as a whole, but that will likely change in the future. If something is broken or the colors look atrocious under some setups let me know and I will try fixing it.

Are you able to change the status line in your favorite text editor? If yes, what kind of information do you put there? Have you written your own status line or are you using a plugin written by someone else?

Posted in programming | Tagged | 2 Comments

Iron Man 3

Iron Man 3 is the first of the post-Avenger era Marvel movie. Joss Whedon’s epic super hero romp is a tough act to follow, both in terms of quality and box office success (which are not the same thing mind you). Before he helmed the big Marvel Universe cross-over the singular hero movies were all we got and we liked them. However, once the audiences got a taste of having Iron Man, Captain America, Thor and The Hulk in the same movie, one must wonder if they will still enjoy watching them adventure on their own. So the first post-Avengers film has to prove that a single hero story-line can still carry a movie.. And that it can do it without Joss Whedon’s writing and direction.

That’s not the only reason why Iron Man was a tough gig though. It also had a difficult task of reconciling the Iron Man continuity with the events that happened during the Avengers. Whedon didn’t really need to worry as much about reconciling all the plot threads from all the different movies because he was building something new and something bold and he could just pluck the heroes from their element and put them on a flying aircraft carrier. However, Iron Man 3 returns Tony Stark to his own established setting, with a cast of established characters (Pepper Pots, Happy Hogan, Col. Rhodes, etc..). It needs to tie the old with the new somehow, and this is especially difficult in terms of Iron Man mythos.

Iron Man 3

Iron Man 3

Thor is an alien space-god who fights frost giants and sorcerers with Clarktech magic so it is easy to hand-wave anything on his continuity. Captain is a displaced fish out of water character so anything that happens to him is essentially a blank slate – you can go anywhere with this hero right now and no one will probably make fuss about it. But Iron Man had two movies to establish his own setting. There is a thematic continuity and certain kind of feel to the Iron Man movies and you sort of must at least try to maintain that in order to make a successful sequel because that’s what people want to see. The problem is that in the last two movies Tony Stark fought relatively low powered (at least compared to Loki) rivals in power armors, and magic alien space gods were not even on his map. Going back to that place would be counter-productive.

I must say that Drew Pierce and Shane Black did an admirable job tying the two continuities into one by addressing the dissonance between them directly. Instead of ignoring the world changing events that happened in New York, they become a central point of Tony Stark’s character arc (yes, Tony has an arc in this film – this is new and definitely a welcome addition to the Iron Man franchise). After fighting alongside gods and monsters, the hero feels somewhat inadequate. Thor, Cap and Hulk all have super powers and can fight alien space monster with their bare hands if need be. Iron Man on the other hand is powerless without his armor, and Stark is all too keenly aware of that. Events of Avengers have shook him to the core, and he is still suffering night terrors and panic attacks triggered by memories of the giant wormhole in the sky. As if to compensate, he fills his house with ever more powerful variants of his armor and finding new ways to get the armor deployed and combat ready as fast as possible. Of course it is all for nothing, and he is soon stripped from his high-tech weapons and forced to overcome his insecurities fighting super-powered villains with nothing but the power of his intellect.

This is a solid character arc, and a solid foundation for a plot: something the previous two Iron Man movies didn’t really have. The second installment especially was rather aimless, directionless mess and the third movie is definitely an improvement over that.

A lot of people seem to be upset about the Mandarin bit, but lets face it: was anyone really expecting him to show up looking like Lo Pan from Big Trouble in Little China in this day and age? As much as comic book readers might be fond of the character, the truth is that the original character concept was somewhat racist. The updated movie version (a middle-eastern terrorist with oriental flair trappings) seems not only much more timely but also quite subversive. When Ben Kingsley showed up on the screen I couldn’t believe how calculated his character design was: this Mandarin was the sum of all post 9/11 fears made flesh. Part Bin-Laden, part Kim Jung Il, part super-villain mastermind he was the picture-perfect boogeyman that proponents of the war on terror have nightmares about.

Speaking of Mandarin, let’s talk about the big twist. If you haven’t seen the movie and don’t want to get spoiled I suggest you skip over the stuff in the gray box below.

Did I like the twist? Did you like it?

At first I didn’t really know how to feel about the non-Mandarin. The more I think about it, the more I like it. Perhaps it is because I was never that attached to Iron Man comics and I don’t really care about Mandarin as a villain. So tweaking his back-story and his powers in an amusing way didn’t really rub me the wrong way. At the same time as I was watching the movie, I felt that Kingsley’s version of Mandarin was just a little bit too on the nose. It was too calculated and cartoonish in all the wrong ways so it was a relief to find out he was a decoy – and a brilliant one at that. Not to mention the fact that Kingsley is wickedly funny as the washed up actor.

You also have to keep in mind that the last two Iron Man movies completely bastardized and ruined other prominent Iron Man villains so expecting this installment to do any different seemed silly. It looks like Joss Whedon is the only super-hero writer in Hollywood who can currently write fun, compelling and enduring villains and I did not expect that to change overnight.


The acting was pretty decent in this one: Kingsley was great, Downey was doing his thing as he always does, Gweneth Paltrow actually got to punch things… Though only after prolonged session of damsel in distress bondage. The kid was quite terrible, as all children in movies are but at least he was able to set up one of the funniest Downey lines in the movie.

Guy Pierce however was kinda annoying. I can’t really put my finger on it, but something about his performance bothered me. I didn’t necessarily hate him – when an actor can actually make you hate his villain then he is actually doing his job well (see Jack Gleeson, aka Joffrey Lanister – the most hated kid in America and Westeros right now). Pierce’s character just felt a bit boring. Granted it might just be that he was completely eclipsed and overshadowed by Kingsley and Downey in terms of the on-screen presence.

All in all, I think the movie was pretty solid. It might be one of the best installments in the Iron Man franchise so far – or at the very least, better than the second movie. It had a good character arc, some fun plot twists and pretty decent dialogue. Granted, it was not without flaws (movie children usually ruin shit pretty fiercely) and plot holes… For example: can someone explain to me why didn’t Tony open up his indestructible bunker that contained an army of remote operated Iron Man suits earlier? Like right away after crashing in the snow? Or when he got his suit powered up again? Because I can’t fucking figure it out.

Posted in movies | Tagged , | 6 Comments

Python: Increase Your Zen, Maximize Your Hapiness

The philosophy of Python can be summed up in a single line:

python -m this

When I first discovered Python it still had that ugly, pixelated green snake logo all over their website, and the documentation was all like “Monty Python guise, LOL, amirite?”. Over the years it has grown up a lot and became so mature, solid and reliable that people no longer even care about the white space thing as much. For years now Python has been ordinary and almost boring – all the rock stars, novelty chasers and cool kids left it for Ruby long time ago (and then recently left Ruby for things like Haskell and Node) and so serious shit can get done.

But despite being stable and mature environment, Python code is still a joy to work with. The beauty of the language is it’s enduring quality, baked right into the syntax and grammar of the language, and deeply rooted in the community. But as with all languages that have been around for a while, Python is not impervious to cruft, baggage and just plain poor coding. Despite the design of the language it is actually not that difficult to write ugly Python code. It is also not that hard to write pretty good code but in a way that is less than optimal.

So I wanted to share some tips, tricks and best practices for writing Python code that I have picked up from various sources over the years. This is definitely not an exhaustive or all-inclusive list. Rather it is a random assortment of suggestions and ideas that can help you structure your code better, and tools that will help you to do more with less.

Use Virtualenv

Installing packages globally is not always good idea. Especially if you use easy_install which can do funky things such as partial installs caused by network connectivity issues. It is better to keep your global install relatively clean and only install random packages on a project per project basis. Then, even if you mess up your installation you can just wipe the slate clean and start over again without much hassle.

Python doesn’t have native support of installing packages and modules this way, but you can force it to do so using the virtualenv package. The idea behind it is rather simple: you run a command line script and it copies your python environment into the current working directory, and then modifies your path for the current session so that all calls to python search the local folders first.

Here is an example how you would create a virtual environment for your project:

# Copy a clean install of python with no packages to ./Foo
# It will create ./Foo if it doesn't exist
virtualenv --no-site-packages Foo
cd Foo
 
# Update path for current session
source bin/activate

This gives you a clean slate instance of Python with no baggage, which you can now build up with only the packages that are required for your project. Granted, this method litters your project folder with bunch of standard library files which can be annoying.

I usually recommend using virtualenvwrapper alongside with the virtualenv package which provides a set of wrapper scripts that aim to simplify your life. Once you install it, you can define $WORKON_HOME environment variable (usually ~/.virtualenvs) which is going to be the default directory for installing virtual environments. It also simplifies the syntax a little bit, and modifies your prompt to reflect the virtualenv you are working in:

# Create virtualenv in $WORKON_HOME/Foo
mkvirtualenv Foo
 
# Activate virtualenv
workon Foo

The great thing about this approach is that you can have two separate environments (say ENV1 and ENV2) for the same project. For example if you want to investigate a bug that only happens when your code is running on a legacy version of Django, you can easily set it up.

Use pip instead of easy_install

One could argue this is a matter of personal preference, but I personally think that using pip should be considered one of the fundamental best practices for Python. As package managers go, it is simply superior in almost every conceivable way. It has meaningful error messages, it doesn’t leave your system in a weird state if an install fails, it can talk to source control repositories and it provides an uninstall command which lets you easily remove old or deprecated packages you no longer use.

It also allows you to create and use simple text files to track dependencies for your project. You simply create a file (let’s call it requirements.txt like this, simply listing names and versions of packages that need to be installed on the system in order for your code to work:

MyProject
Markdown==2.3.1

Save it with your code, commit it to the repository and forget about it. Later, when you need to deploy it somewhere else you can simply tell pip to fetch all the dependencies like this:

pip install -r requirements.txt

If you are using virtualenv, you can actually easily test that this works by creating an environment with the –no-site-packages switch. Or, if you already have a virtualenv custom-tailored to your project you can run the following command to auto-generate requirements file for yourself:

pip freeze > requirements.txt

Note that this typically dumps all the installed packages into the file, so if you run it globally instead of in a virtualenv you can end up with a really long list of packages that may or may not be related to your project.

Standard Libraries are not always best

Python code is beautiful, except when it isn’t. Most of the standard libraries follow the simple philosophy of Python Zen: they facilitate writing beautiful, simple, flat and sparse code. That said, the standard library has a few ugly warts: like urllib2 for example.

Take the following code snippet for example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import urllib2
 
url = 'https://api.github.com'
 
req = urllib2.Request(url)
 
password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None, url, 'user', 'pass')
 
auth_manager = urllib2.HTTPBasicAuthHandler(password_manager)
opener = urllib2.build_opener(auth_manager)
 
urllib2.install_opener(opener)
handler = urllib2.urlopen(req)
 
print handler.getcode()
print handler.headers.getheader('content-type')

Is this beautiful? Is it clean? To me, the entire library has a very heavy handed Java feel to it. Compare it to the same functionality implemented using the third party requests library by Kenneth Reitz:

1
2
3
4
5
6
import requests
 
r = requests.get('https://api.github.com', auth=('user', 'pass'))
 
print r.status_code
print r.headers['content-type']

I think that most of us would agree that the latter is cleaner, clearer, more readable and arguably more Pythonic than the former. While it may seem counter-intuitive at first, sometimes picking a few good external packages can make a difference between unattainable mess and a clean and beautiful code.

If at any point you find yourself writing Python code that seems ugly, dirty and cumbersome, chances are there is a better way. You just have to look around a bit.

Use Context Managers

When you are writing code, chances are that sooner or later you will run into a situation where you need to open, lock or reserve some resource and then release it afterwards. The most trivial example would probably be writing to a file:

1
2
3
f = open('myfile','w')
f.write('Hello world!\n')
f.close

The unfortunate truth about code like that is that most of us habitually forget about like #3. And even if we don’t forget it, an exception or an error might prevent it from being ran. This may not happen so often when doing simple I/O but the same pattern is used to connect to databases or manipulating sockets where errors and exceptions are to be expected as a fact of life, and closing and releasing resources is doubly important. You could wrap your code in a try-finally blocks, but as of Python 2.5 and higher the cleaner and simpler way of writing the above is:

1
2
with open('myfile','w') as f:
	f.write('Hello world!\n')

The cleanup is implicit, automatic and triggered whenever you leave the context of the block. This works great with objects, classes and functions that support it, but how do you bake it into your own custom code? It’s relatively simple: you put your set-up code in an __enter__ method and your tear-down code in an __exit__ method and they will be auto-magically called whenever your class is initialized using the with context manager:

1
2
3
4
5
6
7
8
9
10
11
12
# set it up
class DBConnect:
    def __enter__(self):
        # establish db connection
        return self.dbconnection
 
    def __exit__(self):
        self.dbconnection.close()
 
# use it like this
with DBConnect() as db:
    # do stuff

Defining these methods for your custom classes not only makes the code more robust, but also more beautiful, allowing you to avoid writing the unseemly try-finally blocks all over the place.

Create Objects that are Transparent

The Python REPL can be extremely useful tool. I use it all the time to quickly test ideas or poke my code around. Unfortunately it is not always easy to glimpse inside your custom classes and objects this way unless you take steps to make them transparent. For example, let’s say you have a class like this:

1
2
3
4
class Foo:
    def __init__(self, x=0, y=0):
        self.x=x
        self.y=y

The problem you may run into is that objects initialized from this class do not display any useful information when invoked directly or printed in the REPL:

>>> t = Foo()
>>> f
<__main__.Foo instance at 0x02C82940>
 
>>> print(f)
<__main__.Foo instance at 0x02C82940>

A lot of people know that you can simply override the __str__ method to get a nice string representation of your object that can be printed directly, or concatenated to some other text. It is however far less common to see the __repr__ method implemented in a class. It is a pity, because it controls what is displayed in REPL when the object is invoked directly and as such can be tailored to display developer/debug friendly information about the internal state. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Foo:
    def __init__(self, x=0, y=0):
        self.x=x
        self.y=y
 
    def __str__(self):
        return '({},{})'.format(self.x, self.y)
 
    def __repr__(self):
        return '{}(x={},y={})'.format(
            self.__class__.__name__,
            self.x,
            self.y)

Will behave like this in the REPL:

>>> foo = Foo(5,7)
>>> f
Foo(x=5,y=7)
 
>>> print(f)
(5,7)

Implementing the __repr__ method may seem unimportant and insignificant, but it saves lives.. Or at least man hours of debugging.

Lint Your Code

I’m a firm believer in linting your code. It is a good practice that tends to yield saner, more beautiful and readable code most of the time. A lot of people don’t like very aggressive linters because they tend to complain about trivial things such as tabs vs. spaces, lines longer than 80 characters and etc. You should keep in mind however that every dumb linter rule is there for a reason, and generally adjusting your coding style a bit to conform to said rules is never really a bad idea. Granted, if you are working with an existing code base that has never been linted, you might be shocked how much refactoring it would take to get it in shape. But when you start a new project, a rigorous linter is a great thing. It will not only help you structure the code, but it will also catch minor bugs that could otherwise be overlooked.

Personally I’m a fan of PyLint which tends to be super anal and very, very harsh on you. It actually scores your code, runs statistical analysis on it, and keeps track of last few runs so that you can see how much your changes have improved the overall quality of code.

Obviously PyLint is an external tool, but you can also get in-editor, as-you-type linting tools. Sublime has the excellent Sublime Linter which does more than just Python. If you run Vim there is a plethora of plugins that do just that, with the phenomenal Syntastic leading the pack. If you use Emacs then… Then ask Chriss – he will tell you what to use.

I highly recommend using PyLint in addition to any in-editor tool for the aggressive harshness and neat statistics it provides.

Always Be Testing

I don’t think I have to stress the importance of testing your code. At the very least you should be writing unit tests for all your classes. Python fortunately has a built in unit testing framework aptly named PyUnit. It is pretty much the industry standard and it follows the same conventions as JUnit and PHPUnit. If you have used these unit testing frameworks, PyUnit code should immediately look familiar and understandable:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import unittest
import Foo
 
class SimpleTestCase(unittest.TestCase):
 
    def setUp(self):
        """Call before every test case."""
        self.foo = Foo()
        self.file = open( "blah", "r" )
 
    def tearDown(self):
        """Call after every test case."""
        self.file.close()
 
    def testA(self):
        """Test case A. """
        assert foo.bar() == 543, "bar() not calculating values correctly"
 
    def testB(self):
        """Test case B"""
        assert foo+foo == 34, "can't add Foo instances"

If you want to do something along the lines of acceptance testing, then Splinter is probably the way to go. It has really concise and clean API and lets you create complex tests for web applications fairly easily. The only downside is that it is not really a full fledged test framework like Codeception for example. There is no way to assert or fail tests in splinter – it is meant to be used as an abstraction layer or a component. So you basically just write PyUnit test cases which use Splinter, which works quite well as you end up with all your tests running on the same framework in the same place.

Use a build tool

As you may or may not know, I am a big fan of Rake as a simple build tool. That said, it doesn’t really seem all that kosher (or practical) to use a Ruby build tool for Python projects. Fortunately there is Paver which is essentially Rake of Python world, though perhaps not nearly as popular.

I believe that originally it was created to streamline the creation of distribution bundles and packages, but you can confidently use it to run any number of arbitrary tasks. Like with Rake, your build file is an executable script – you don’t configure your build, you code it. This makes it endlessly extensible and perfectly suited for our puposes.

To start using Paver you just pip install paver and create a pavement.py file somewhere in your project directory. An example file could look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from paver.easy import *
 
@task
def lint():
    print "Linting..."
    # run linter 
 
@task
def test():
    print "Testing..."
    # run your unit tests
 
@task
@needs(['lint', 'test'])
def default():
    pass

You can run it like rake from the command line:

# run lint task
paver lint
 
# run the default task
paver

It is usually a good idea to automate running of your linter and your unit tests with Paver. It allows you to make some changes, then immediately have them analyzed for errors and bad code smells, and ran through all your test cases.

Suggestions?

I hope this was helpful to at least few people out there. I am by no means an authority on Python but I feel like some of these tips can be useful for both novices as well as seasoned programmers. I generally enjoy reading this sort of write-ups because even if I already most of the stuff in the article is always a chance that I will learn something new. What are your favorite Python tips? Have you ever stumbled upon a Python related article or a video which made you go “Wow, this changes everything!”. If so, please share it in the comments.

Posted in programming | Tagged | 1 Comment