Print E-mail

Python, thanks to Lisp

Last Updated on Tuesday, 20 March 2012 19:33

There is a Python application I’m currently working on, where for one moment I was sorry that I don’t write it in Lisp (I don’t know Lisp well, and it sometimes comes to bother me..)

In the application I use data persistence between activations. The data structure holding all the persistent data is a dictionary. Whenever I needed to search for a key in the dictionary I used the following code:

if ‘some_persistent_data_key’ in global_dict:
    do_something_with(global_dict[‘some_persistent_data_key’])
else:
    do_default_action()
The keys are long strings, and it’s needless to say that there is a code smell here, repeating the key twice. So I changed the pattern a little bit:
key = ‘some_persistent_data_key’ 
if key in global_dict:  do_something_with(global_dict[key])
else: do_default_action()
So now I didn’t repeat the key, and I could also join some lines, since they were now shorter, thanks to the short variable name, key.

But I wasn’t satisfied. The pattern was still too verbose to my taste. I wanted something with more pattern. You can say the above code has a pattern, but it’s a very loose one. I also wanted to abstract away the use of the dictionary.

Then I thought about Lisp macros. With a Lisp macro I could do:

(with-key "some_persistent_data_key" exist value 
    (if exist (do-something-with value))
    (else (do-default-action)))
where exist and value are variables that are created and assigned by the macro with-key.

Or, even better,

(with-key "some_persistent_data_key" value 
    (do-something-with value) ; if exist
    (do-default-action))  ; optional - if doesn't exist
This is nice, because of the pattern specific to the task (although it has the same number of lines).

But giving to this a second thought, I figured that I could do almost the same in Python. Given the helper function:

def with_key(key):
    if key in global_dict:
        return True, global_dict[key]
    else:
        return False, None
I could now write:
exist, value = with_key(‘some_persistent_data_key’)
if exist: do_something_with_value(value)
else: do_default_action()
This is more like it.

Sometimes you need to search elsewhere, only to find that the answer is in your hands already.

However, I suspect that had I used Lisp regularly I would have done better programming in any language. The reason is simple. Lisp contains more programming idioms and techniques than other languages, and those idioms and techniques, once mastered, become one’s mind’s tools for developing software. The more tools you’ve got, the better programs you write, even in languages that lack those techniques, needless to say languages that do have them.