Wednesday, January 6, 2010

list comprehensions in python

One of my favorite features of python is a functional language feature that python itself borrowed - list comprehensions.

I just think it is wonderfully elegant if a language can do something like this:

Example 1:

lines = ['now is the time\r\n']
lines.append(' for all good men ')
lines.append(' to come to the aid of their country\n')

# Does not modify list, returns a new list
lines = [line.strip() for line in lines]

print lines

>>>['now is the time', 'for all good men', 'to come to the aid of their country']

Example 2:

lines = ['<act> is the next act']
lines.append('performing at our show')
lines.append('please give <act> a big round of applause')

print [line.replace('<act>', 'Go Dog Go') for line in lines]
print [line.replace('<act>', 'The Beatles') for line in lines]

>>>['Go Dog Go is the next act', 'performing at our show', 'please give Go Dog Go a big round of applause']

>>>['The Beatles is the next act', 'performing at our show', 'please give The Beatles a big round of applause']

You can do simple operations like strip and replace or even an in place lambda on every element of a list and return that list... all in one line.

I love Python and its functional cousin languages.

hibernate console in intellij idea 9

I was pleasantly surprised to find better hibernate support in intellij idea 9, which was recently released.

They had hibernate support in 8.x, including a console, where you could run queries against your data using the mappings you had configured. However in version 9, they added the ability to use named parameters with associated values. So in essence, you can paste in a hql query and it autodetects the named parameters, e.g. :username. That pops up on the right pane as a named paraemeter. You just double click that, set its value, and you can run the query.

intellij has had support for this in their jdbc console in the past, but it's very handy now with the hibernate console. It removes one step from having to debug queries - you no longer have to use just the sql output that hibernate outputs and then piece queries back together and then try to guess where the disconnect was :).

See intellij feature request:
http://youtrack.jetbrains.net/issue/IDEADEV-41129

Related to hibernate console, don't forget to have the ehcache.jar in your module's classpath if you want to use the hibernate console. You can find the jar in the basic core download of hibernate - in the lib/optional/ehcache directory of the bundle. The console requires the secondary cache and will give you odd secondary cache errors if you don't have it in the path.

See this about loading ehcache:
http://youtrack.jetbrains.net/issue/IDEA-21914