News for hackers. Stuff that matters.
Re:Tracing Python by peterkelly on Wednesday May 24, 2023 @11:07PM (#36066670)
Python has a built-in API for tracing: https://docs.python.org/3/library/sys.html#sys.settrace

Here's an example of how to use it (obviously a minimal case, you can customise your handler do do whatever you need):

    def mytrace(frame, event, arg):
        if event == "call":
            print("call", frame.f_code.co_name, frame.f_locals)
        elif event == "return":
            print("return", frame.f_code.co_name, arg)
        return mytrace

    import sys
    sys.settrace(mytrace)
For example, given the following code:

    def three(z):
        return 3

    def two(y):
        return three("BBB") - 1

    def one():
        return two("AAA") - 1

    one()
It will output:

    call one {}
    call two {'y': 'AAA'}
    call three {'z': 'BBB'}
    return three 3
    return two 2
    return one 1
Re:Tracing Python by taeric on Wednesday May 24, 2023 @11:49PM (#36066878)
I confess I'm surprised the builtin wasn't one of the demoed options. Curious what the reason is.
Re:Tracing Python by isotopp on Thursday May 25, 2023 @03:34AM (#36068000)
I just pushed an addendum, and it is being rendered right now.
Re:Tracing Python by taeric on Thursday May 25, 2023 @11:16AM (#36071813)
Kudos on making the update! Makes sense that you might not find it if you didn't know it was there. Python's "batteries included" means most things you may want to do, you should check to see if there is a standard lib option, as well. Sometimes it is barebones enough that you may want more, of course. So, really nice to see all of the options you presented.
Re:Tracing Python by yi_xuan on Thursday May 25, 2023 @01:47AM (#36067422)
Pdb also employs this approach for debug. I had wondered about pdb's implementation, when I saw it, I felt a little surprised.
Re:Tracing Python by RJIb8RBYxzAMX9u on Thursday May 25, 2023 @02:07AM (#36067520)
Wow, I can't believe I didn't know about this until now! I'm the lucky 10k[0] today.

[0] https://xkcd.com/1053/