callerframe package¶
Module contents¶
The callerframe decorator adds a __caller_frame__ global attribute to the decorated function’s globals; this attribute refers to a FrameInfo object containing information about the caller function:
- frame: the caller’s frame;
- filename: the name of the file where the function has been called;
- line_number: the line number of the call in filename;
- function_name: the name of the caller function;
- context: a list of source line containing the call;
- index: the index of the line in context where the function has been called.
>>> @callerframe
... def log(kind, message):
... print("{}: function {}: {}".format(kind, __caller_frame__.function_name, message))
...
>>> def foo():
... log("error", "lost connection")
...
>>> def main():
... return foo()
...
>>> main()
error: function foo: lost connection
The log function receives information about it’s direct caller; but what if we want to have an error() function based on log()?
>>> def error(message):
... log("error", message)
...
>>> def foo():
... error("lost connection")
...
>>> def main():
... return foo()
...
>>> main()
error: function error: lost connection
This is correct, since error() is the direct caller of the log() function; nevertheless we would like to show the information about the error()’s caller instead. In this case it is possible to decorate error() too (no modification is needed in log):
>>> @callerframe
... def error(message):
... log("error", message)
...
>>> def foo():
... error("lost connection")
...
>>> def main():
... return foo()
...
>>> main()
error: function foo: lost connection
In other words, the first decorated function found in the call stack sets the caller information. This information is not overwritten by nested calls to decorated functions.
The attribute name, by default __caller_frame__, can be choosen:
>>> @callerframe("CALLERFRAME")
... def show_caller():
... print(CALLERFRAME.function_name)
...
>>> def foo():
... show_caller()
...
>>> foo()
foo
-
class
callerframe.
FrameInfo
(frame, filename, line_number, function_name, context, index)¶ Bases:
tuple
-
__getnewargs__
()¶ Return self as a plain tuple. Used by copy and pickle.
-
__getstate__
()¶ Exclude the OrderedDict from pickling
-
static
__new__
(_cls, frame, filename, line_number, function_name, context, index)¶ Create new instance of FrameInfo(frame, filename, line_number, function_name, context, index)
-
__repr__
()¶ Return a nicely formatted representation string
-
context
¶ Alias for field number 4
-
filename
¶ Alias for field number 1
-
frame
¶ Alias for field number 0
-
function_name
¶ Alias for field number 3
-
index
¶ Alias for field number 5
-
line_number
¶ Alias for field number 2
-