An easy way to get the line number of your python code

Sometimes you just want to know where things are in the script when you are debugging.  Or where things came from.  You can pass that information or report it while debugging using this snippet.  Easy, simple.

import inspect

def lineno():
    """Returns the current line number in our program."""
    return inspect.currentframe().f_back.f_lineno

print "this is line", %lineno()
print  " the line number, %s, is in the middle of this sentence"%lineno()
i = type(lineno())
print i

results in :

this is line number 8
the line number, 10, is in the middle of this sentence
<type 'int'>

Note that the line number is type integer.

Thanks to the Danny Yoo and the Active State recipes for this easy tip.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s