Wednesday, November 19, 2008

Nice trick with functools and os.path.join

Sometimes os.path.join('something', 'something_else', 'more' ... ) gets old. With functools.partial, you can preload os.path.join to clean up your code. For example:

import functools
my_path_plus = functools.partial( os.path.join, 'a', 'b', 'c')
m = my_path_plus('x', 'y', 'z')
# m is 'a/b/c/x/y/z'
n = my_path_plus()
# n is 'a/b/c', for when you don't want to add anything.