Wednesday, December 1, 2010

Python: Doing it right the first time

Python has matured as a language now and the most prominent sign of it was it breaking backward compatibility to make space for more advanced features in the future. However, with maturity comes a slew of expected but not required conventions which have quickly developed around Python. This is a cheat sheet of good formatting tips, tricks and links for those new to the language. I have gathered during my slips and falls in using Python, and I hope these might help a newcomer avoid the no-you-are-doing-it-wrong moments too late into the project.

  1. PythonTidy: This is a nifty and updated script (v1.21 on 3rd Sept. 2010) by Lacus Veris which can do easily perhaps what you have dreaded to do on slightly older code: refactoring to meet standards! I had to do the following change on my system to make the script produce newlines in the output, but overall I was very satisfied:

    - OVERRIDE_NEWLINE = '' # 2006 Dec 05
    + OVERRIDE_NEWLINE = '\n' # 2006 Dec 05
  2. PyFlakes: It is a lightweight Python code checker (like PyChecker) which can notify you of minor by annoying python coding errors (like misspelling a variable name, forgetting to import a module, etc.) The checks are done in real time and can save some serious swearing and editor-to-terminal switches if you use it as a Vim plugin. However, it does not inform the coders of the styling violations. For that, consider PyLint (see later).
  3. PyLint: Pylint actually compiles the code and shouts out errors and standard style violations. There is a Vim plugin to do it each time you save the Python file. Working with a large script can get difficult if you :w as frequently as I do. However, one feature I really like is the code rating it shows after analyzing the code. 
  4. Pindent: This is a script which makes Python code slightly easier to understand. It adds some # end tags to the code after closing if or def blocks.
  5. Python project directory structure: I spent quite sometime trying to get this right. Jp Calderone has spelled out most of the rules here. Also, the Python documentation too has a few things to say about the matter, specially about the differences between a Module and a Package.
  6. Python and Vim: If you are a Vi fan, like me, then you would love these scripts by Marius Gedminas. They definitely make Vi a more powerful IDE for Python than any other I have seen out there.
  7. Style Guide for Python Code (PEP 8): This is the coding standard style book for Python: a must read before anyone writes a serious project. There are some things which the Python documentation skips perhaps because of brevity, perhaps because these are not required conventions or perhaps just because programmer are lazy, but this PEP is comprehensive and well thought out. This document is what is used for the default definition in PyLint and PythonTidy's default styling.
 If I had known these before, my initial attempts of serious projects would have fared much better. I hope they help you out.

~
musically_ut

    Wednesday, November 24, 2010

    Bible Camp Bloodbath: A Book by Joey Comeau

    Did you like Saw?
    If you say yes, then stop reading this review, read the real thing.

    If you said no, then imagine reading it in a book. Sounds more docile? Easier than seeing someone sawing their femur? Think again.

    The book begins in the same surreal world which anyone who has appreciated A Softer World is familiar with. Unconventional to say the least, but still befitting what is to follow later. The writing eerily reminds one of Lullaby time Palahniuk. The pace of the story is also the same: The novel is short (only 13 chapters) but this increases the started-running-and-ran-into-a-brick-wall feel.

    I am being honest here when I say that I am not a fan of gore, but the story managed to have enough, just enough, grip to keep me engaged with my teeth on the ends and eyes refusing to blink.  And it was not the same instinct which makes one turn one's head to see a mutilated body at a car-wreck. It was the artful story. Joey mixes a cliqued idea with something so bizarre that while reading one only has a faint deja-vu, but remains too engaged in reading to figure out what is happening.

    Finally, the last chapter provides a perfect finish to the fast paced tale.

    If not anything else, then it will be a memorable read which will stay with (I resist the temptation to write haunt) you for a long time.

    The book can be read online, can be purchased for Kindle, or as a hardcopy.

    Thursday, November 18, 2010

    Python scripting

    There are a few things which are easily overlooked while scripting using Python CLI.

    1. Reloading modules: I generally program with a module structure, while maintaining documentation and test suite simultaneously (Using doctest). To quickly reload modules, I use the reload command:

      >>> import My.Very.Large.Module.Name as M
      >>> M.this_function_to_test( with_these_arguments )
      Python: Umm ... there is a bug on line number ***

      (* making changes to My/Very/Large/Moudle/Name.py file *)

      >>> reload(M)
      >>> M.this_function_to_test( with_these_arguments )
      Python: Yeah, I think it works now, but you might want to fix ***

      (* more fixing *)

      >>> reload(M)
      >>> M.this_function_to_test( with_these_arguments )
      Python: Perfect, now the turn of world poverty, go solve.

      >>> pack_bags_and_leave()

      However, there is a caveat here: If you have changed the name of the function to test, then the old name will still persist and calling M.this_function_to_test( ... ) will continue to return the results of the old version. Hence, old functions will not be dropped automatically from the namespace.
    2. Reverse Intelligent Search: I knew of this feature in my bash shell, but did not know that Python CLI had it too! To search for an old command used on the CLI, hit Ctrl-R and type a few words and Voila!
    3. iPython: This interactive shell for Python has many many features, but the killer feature for me is the bash-like Tab Completion!

    As I find more, I'll keep putting them up here.

    Saturday, November 13, 2010

    Get more play count information in Rhythmbox

    I am obsessed with keeping track of what my musical taste is like, and to be able to get quantitative as well as qualitative information about it. Last.fm (and now libre.fm)with audio scrobbling (both via Rhythmbox as well as my old iPod Shuffle), satiates my needs for numbers most of the time, but I would like to know a little more. Initially, I just wanted to know which is the album I listen to the most, but it could easily be generalised to much more easily.
    Hence, I made a small plugin extra-playcount for Rhythmbox, (Note: It maybe better to get more recent version of the files from the launchpad code branch) which gives me just that little bit more information. To see the plugin in action, select multiple songs and select properties to get an extra tab in the info window.
    The additional data presented is:

    1. Number of songs by each artist
    2. Playcount of songs by each artist
    3. Number of songs in each album
    4. Playcount of each album
    For bug tracking and development I have set it up as a project on launchpad here.

    Installation instructions:
    • Extract the contents of the tar ball in home_directory/.gnome2/rhythmbox/plugins
    • Restart Rhythmbox.
    • Go to menu Edit → Plugins and enable Extra-Playcount

    extraPlaycounts.jpg
    Extra playcount plugin in action in Rhythmbox

    Getting Rhythmbox to play desired songs in awesome

    Awesome is a pretty good tiling window manager I have recently taken some liking to. I initially started with it for the simple reason that I was working with a Matlab script which spawned tens of figures and I wanted to view them simultaneously. I am sure there are easier ways of viewing those graphs than switching window managers from Gnome (which I still think is pretty good) to Awesome, but it was a valid reason to procrastinate in my own way. :-)
    Anyhow, some of the things I really missed from Gnome were:
    1. sticky notes
    2. Gnome-Do and Pidgin integration (opening IM windows by just Super + Space + Buddy name )
    3. Gnome-Do and Rhythmbox integration (playing songs by just Super + Space + Song name )
    It is the last thing which I got tired of today and looked at how I can fix it. The configuration turned out to be fairly easy to, thanks to the general awesomeness of Awesome and handy Lua documentation. It happened in the following steps:
    1. Getting to know rhythmbox-client can play songs using their URI, which is just the path of the file in case of local files.
    2. Understanding how to configure awesome using /.config/awesome/rc.lua
    3. Figuring out how to get a prompt to type in a song name, which turned out fairly simple thanks to awful.prompt
    4. Understanding functions in Lua and writing functions for Notification and running the rhythmbox client:

      myRhythmboxFunction = 
      function (c)
      home = os.getenv("HOME")
      file = io.open(home .. "/.song_list")
      if not file then
      myNotifyFunction("~/.song_list does not exist")
      else
      found = false
      myNotifyFunction("Searching for " .. c)
      c = string.lower(c)
      for song in file:lines() do
      songLower = string.lower(song)
      if string.find(songLower, c) then found = true awful.util.spawn ("rhythmbox-client --play-uri=\"" .. song .. "\"") myNotifyFunction("Found, playing") break end end file:close() if not found then myNotifyFunction("Not found") end end end


      It is not difficult to guess what this function does:
      • Open the file /.song_list
      • Read one line at a time and figure out whether the parameter $c$ occurs in the string or not (not very robust)
      • If so, great! Play it!
      • Otherwise, if no song is found, display a notification and let things be
      I have not described how I made myNotifyFunction , because it is embarrassingly simple to implement using naughty, but I did it in a horribly complicated way using awful.util.spawn and notify-send . But, hey! This is just supposed to be a proof of concept, right? :-)
    5. Understanding how to add global key bindings:
      awful.key({ modkey,           }, "p",
                 function ()
                   awful.prompt.run({ prompt = "Play: " },
                   mypromptbox[mouse.screen].widget,
                   myRhythmboxFunction,
                   nil)
                 end),
      
      Here, mypromptbox is just the usual Run prompt which I have borrowed to act as the play prompt box.
    After these rudimentary changes, I did:

    find /my/music/folder | grep -v 'No directories' > ~/.song_list 

    To prepare the .song_list file needed in myRhythmboxFunction , and voila!
    My songs are now Super + P + Song name away!
    The next additions on my dashboard are the Pidgin integration and some sort of periodic mail notification without needing either evolution or thunderbird running in the background.
    Some other holiday ...

    Automatic playlists in Rhythmbox

    This is a neat trick that I didn't know Rhythmbox had up its sleeve. I have made a few automatic playlists which keep me a little closer to my songs:

    1. Play count > 5 and last play time is at least a week before.
    2. Play count = 4
    3. Rating 4 stars and play count > 4
    4. ...
    This option is available in menu Music -> Playlist -> New automatic playlist.
    If you haven't already, you must give it a try!