brockj.net

January 20, 2009

I want to be like Peter Norvig when I grow up

Filed under: Uncategorized — brock @ 7:12 pm

I recently stumbled up Norvig’s write up of some of the intracacies of Java, although originally written about ten year ago. It comes in the form of an IAQ: Infrequently Answered Questions. He gives a similar treatment to Python. Reading some of his other articles, you get a sense of his inquistive and yet humorous nature.

September 25, 2008

Annotating functions and classes in Python with decorators

Filed under: Uncategorized — brock @ 7:47 pm

One feature of Python that I discovered by accident while looking through Django code is “python decorators” with which you can annotate your functions and classes. Details about the feature and it’s possible uses can be found here.

Here is an example decorator that I wrote:

def print_parameters(f):
  def new_f(*args, **kwds):
          print args
          print kwds
          return f(*args, **kwds)
  new_f.func_name = f.func_name
  return new_f

This decorator creates a new wrapper function, new_f. new_f prints args and kwds from the original function’s signature and then executes the original function. My decorator returns the new function, which replaces the original definition (func_name, the name of the function object, is changed to reflect the name of the original function instead of new_f).

And in action:

>>> @print_parameters
... def foo(a,b,c):
...     print 'this is foo'
...
>>> foo(1,2,3)
(1, 2, 3)
{}
this is foo
>>> foo(1,2,c=3)
(1, 2)
{'c': 3}
this is foo

August 21, 2008

Making a textual status bar/ticker in python

Filed under: Uncategorized — brock @ 8:15 pm

Here is a neat way to print the status of a loop in Python:

def wipeprint(str, static={}):
    laststr = static.get('last')
    if laststr:
        sys.stdout.write('\b'*len(laststr))
    sys.stdout.write(str)
    sys.stdout.flush()
    static['last']=str

#example usage
bignum=100000000
for i in range(bignum):
    if not (i+1) % 10000:
        wipeprint('\nnumba %d!' % (i+1))

It takes advantage of the fact that the default value of static persists from call to call to save some state from the last call.

August 19, 2008

Pimp your svn diff

Filed under: Uncategorized — brock @ 11:11 pm

If you are as lucky as I am and do 99% of you development in PuTTY with no X-server, or you just love using the command-line for everything, you can colorize the ouput of svn diff by piping it into vim:

svn diff | vim -R -

Vim would normally require a tty but adding - will force it to read from stdin. After that, if you are unfamiliar with vim, you just have to know to type :q to get outta there.