all Python 3tracebackfunction
traceback.format_stack()
formatting tracebacks
The current call stack as traceback-style strings, with no exception involved — to log where a function was called from.
Syntax
lines = traceback.format_stack(f=None, limit=None)
It returns a list of strings; the last one is the line calling format_stack itself. Handy when debugging "who calls me with bad arguments": log ''.join(traceback.format_stack(limit=5)). logging has a ready-made equivalent without manual joining — logger.warning('…', stack_info=True).
Examples
import traceback
def deep():
return traceback.format_stack()
lines = deep()
print(len(lines)) # → 2
print(lines[-1].splitlines()[0].endswith('in deep')) # → True
See also
Open in the full glossarydocs.python.orgReport an inaccuracy