23Sep

C __LINE__ equivalent in Python

Posted by Elf Sternberg as programming, python

I started using this recently. If you do a lot of Python, you’ll sometimes find yourself desperate for breadcrumbs, little print statements scattered throughout your code as you try to figure what you told it to do, since it’s obviously not doing what you want it to do. I’d used inspect previously to unravel exception handlers; there’s a customized one inside the Isilon UI, so if the product fails in the field the exception will be logged to a file for later analysis, but this is a nice little routine. It’s basically a pythonic version of the C __LINE__ macro. Wherever you think you might need a debugging statement, put if DEBUG: print _line(), foo, bar, baz and you’ll not only get the fields you want to see, but also the name of the function/method, and the line number of the print statement.

import inspect
def _line():
    info = inspect.getframeinfo(inspect.currentframe().f_back)[0:3]
    return '[%s:%d]' % (info[2], info[1])

Use as needed.

Comment Form

Subscribe to Feed

Categories

Calendar

September 2008
M T W T F S S
« Aug   Oct »
1234567
891011121314
15161718192021
22232425262728
2930