1. 17
  1. 7

    As of Python 3.8, f-strings support = for self-documenting expressions and debugging [1]. Although it doesn’t include the line number, it’s pretty nice for quickly debugging.

    >>> print(f"{1+2+3=}")

    [1] https://docs.python.org/3/whatsnew/3.8.html#f-strings-support-for-self-documenting-expressions-and-debugging

    1. 1

      Ahh…. I knew that something was out there! I had tried f"{1+2:=}" to no avail at one point and it didn’t work, and I hadn’t found anything in the documentation, but I must have seen those release notes at one point

    2. 4

      Neat digging, in a similar vein, PySnooper does the same kinda magic debug printing. See also, IceCream. Would love to see some variant in the stdlib some time..

      1. 2

        It’s also similar to q.

        1. 2

          PySnooper is probably hooking into the debugging trace functions, that let you hook in a callback before executing every line of code (this is also used by stuff like coverage IIRC).

          IceCream is clearly very close to my thing though. And it has, like, test cases. Not a super fan of the ic calling convention but game respects game.

        2. 2

          What about parsing that line as a whole instead of cutting off until the dbg() part? It should provide valid AST and you could just traverse the tree and find the dbg() nodes. Since you wouldn’t be debugging super tricky functions anyway, it wouldn’t be too bad performance-wise, it would just give you the inner expression which you can reconstruct into a string. It would probably not be a 1:1 representation but it should still work pretty fine.

          1. 1

            You hit a variant of the ast.parse problem, since a single line of context might not be parsable.

            For example, if you have:

            if dbg(foo()):

            then your code context (if you’re working on one line through frame) is just if dbg(foo()):, which isn’t fully parsable as an AST node by itself.

            That being said, it might be possible to take the AST of the entire source file, and from there find nodes that cover the line you’re on and look from there. If the information is freely available on the module that might be the cleaner solution.