fork download
  1. import sys
  2. import traceback
  3. from unittest.mock import patch
  4.  
  5. def dump_stack(detailed_types=(), file=sys.stdout):
  6. def detailed_repr(obj, _repr=repr):
  7. def repr_attributes(obj, indent_level=2):
  8. if isinstance(obj, detailed_types):
  9. seen.add(id(obj))
  10. indent = ' ' * indent_level
  11. for name, value in sorted(vars(obj).items()):
  12. yield f'{indent}.{name} = {value}'
  13. if id(value) not in seen:
  14. yield from repr_attributes(value, indent_level + 1)
  15. seen = set()
  16. return '\n'.join([_repr(obj), *repr_attributes(obj)])
  17.  
  18. with patch('builtins.repr', detailed_repr):
  19. print(
  20. *traceback.StackSummary.extract(
  21. traceback.walk_stack(sys._getframe(1)), capture_locals=True
  22. ).format(), sep='\n', file=file
  23. )
  24.  
  25. class Foo:
  26. def __init__(self, x, y):
  27. self.bar = Bar(x, y)
  28. self.foo = self
  29.  
  30. class Bar:
  31. def __init__(self, x, y):
  32. self.x = x
  33. self.y = y
  34.  
  35. def foo(c):
  36. d = c + 1
  37. dump_stack(detailed_types=(Foo, Bar))
  38.  
  39. a = 1
  40. b = Foo(2, 3)
  41. foo(a)
Success #stdin #stdout 0.1s 16620KB
stdin
Standard input is empty
stdout
  File "./prog.py", line 37, in foo
    c = 1
    d = 2

  File "./prog.py", line 41, in <module>
    Bar = <class '__main__.Bar'>
    Foo = <class '__main__.Foo'>
    __annotations__ = {}
    __builtins__ = <module 'builtins' (built-in)>
    __cached__ = None
    __doc__ = None
    __file__ = '/home/wT8L4N/./prog'
    __loader__ = <_frozen_importlib_external.SourcelessFileLoader object at 0x1546bffd5c10>
    __name__ = '__main__'
    __package__ = None
    __spec__ = None
    a = 1
    b = <__main__.Foo object at 0x1546bfba8cd0>
        .bar = <__main__.Bar object at 0x1546bfba8550>
            .x = 2
            .y = 3
        .foo = <__main__.Foo object at 0x1546bfba8cd0>
    dump_stack = <function dump_stack at 0x1546bfab7160>
    foo = <function foo at 0x1546bf9c5a60>
    patch = <function patch at 0x1546bf31dd30>
    sys = <module 'sys' (built-in)>
    traceback = <module 'traceback' from '/usr/lib/python3.9/traceback.py'>