Sunday 3 October 2004 — This is over 18 years old. Be careful.
In C++, if you want your code to talk about itself, you often use the predefined magic macros __FILE__ and __LINE__ to get the filename and line number of the current line:
// Use this macro if you can't write the code yet.
#define NOTYET() NoCodeYet(__FILE__, __LINE__);
void NoCodeYet(const char * pszFile, int nLine)
fprintf(stderr, "No code yet at %s(%d)\n", pszFile, nLine);
NOTYET() // I'll get to this later.
This provides a convenient way to leave breadcrumbs that will direct you to the spot in the code later.
How to do it in Python? With help from the Python Cookbook, I created this. It uses scary functions from sys (_getframe has a leading underscore and is described as “for internal and specialized uses only”):
""" Create a string naming the function n frames up on the stack.
co = sys._getframe(nFramesUp+1).f_code
return "%s (%s @ %d)" % (co.co_name, co.co_filename, co.co_firstlineno)
""" Call this function to indicate that a method isn't implemented yet.
raise Exception("Not yet implemented: %s" % _functionId(1))
This goes one further than the C++ technique, by providing the function name as well as the file and line.
Using one less f_back, you see where the routines was called from. . .
Using 2 f_back's, and then using 1:
"@[file: ...ework\\interact.py, line 257 in 'runcode']"
"@[file: , line 1 in '?']"
note: it might also be usefull to some people to use a similar trick to get the callers caller's variables:
frame = inspect.currentframe().f_back.f_back
return frame.f_globals, frame.f_locals
"""Give linenumer, file, and functionname of the callers,
caller.. Uses the standard module inspect
info = inspect.getframeinfo(inspect.currentframe().f_back.f_back)[0:3]
# Break long filenames
return '@[file: %s, line %s in %r]'% tuple(printInfo)
Get the source with correct indention by running:
(source to create this data can be found on: gwork.blogspot.com
Boost provides a handy macro called BOOST_CURRENT_FUNCTION that is mapped to the appropriate macro based on your current compiler. The macro is #defined in boost\current_function.hpp.
I hope this helps someone out there!
Also, you can use the traceback module to print a traceback, without actually raising an exception.
I saw the code and i thought that it may be very useful to me for finishing a program that i'm making.
But i have a question with the _getframe() function. If i want to get the filename of the current program that it's running, i.e. the path of the self program; which is the argument for _getframe() (in this case nFramesUp+1) that i must input for this purpose?
Beforehand, thank you very much.
Add a comment: