__LINE__ and __FILE__ functionality in Python?

John Machin sjmachin at lexicon.net
Sun Aug 13 08:18:34 EDT 2006


Joakim Hove wrote:
> Hello,
>
> i have simple[1] function like this:
>
>    def log_msg(msg , file , line):
>        print "%s:%s   %s" % (file,line,msg)
>
> the file and line arguments should be the filename and linenumber of
> the source file where the function is called. If this were C I would
> have used the __FILE__ and __LINE__ macros as:
>
>   log_msg(msg , __FILE__ , __LINE__)
>
> Is there a way to emulate this behaviour in Python?
>

It's better in Python not to emulate that but to let the caller do the
work:

C:\junk>type caller_id.py
import inspect

def logger(msg):
    print "logger:", msg
    print "called from %s:%d" % inspect.stack()[1][1:3]
    print

def client1():
    logger("one")

def client2():
    logger("two")

client1()
client2()


C:\junk>caller_id.py
logger: one
called from C:\junk\caller_id.py:9

logger: two
called from C:\junk\caller_id.py:12

If you care to search for __LINE__ in this newsgroup, there's a slight
chance you might find a thread or two or twenty-two on the topic :-)

I don't usually go for one-liners, especially ugly ones like
"inspect.stack()[1][1:3]" but it avoids the risk of hanging on to a
reference to the frame object -- see the warning in the inspect docs.

You can get the name of the calling function or method (and,
indirectly, the method's class) if you want to log the whole dossier --
details left as an exercise :-)

HTH,
John




More information about the Python-list mailing list