Monday, October 4, 2004

__FILE__ and __LINE__ in Python

Ned Batchelder shows how to use sys._getframe() to get the current (or calling) filename, line, and function in Python. In C, this happens at compile-time. Practically everything in Python happens at runtime, so this is slower, but you can also do things like inspect the local variables in the stack frames.

3 Comments RSS · Twitter


You could just use Ruby, which gives you __FILE__ and __LINE__ directly.


I forgot to mention that Python does have the module-level __file__ variable, but it's not as useful as __FILE__ in C, because it can't be hidden inside a macro call. What's the Ruby equivalent of sys._getframe()?


it's called 'caller'

Leave a Comment