1

When debugging, I sometimes find it useful to access the values of local variables within a class method without necessarily invoking pdb.set_trace().

class Calculator:

    # ...

    def add_and_format(x, y):
        sum = x + y
        return '{:.2f}'.format(sum)

If I want to access sum following a call to add_and_format, I could edit the code to be self.sum = x + y and inspect it that way. In the case of many local variables, however, it would be simpler if I could use a @debug decorator around the method or some debug_function() class method to persist all locals variables as attributes. I guess I have in mind something basically equivalent to

def my_method(self, *args, **kwargs):
    # ... method code
    for k, v in locals().items():
        setattr(self, k, v)
    return result

I've seen this answer, which is a good partial solution but I'm unsure how to get it to work for this use case.

Soul Donut
  • 357
  • 3
  • 12
  • 1
    A decorator can't access the decorated function's local variables. They're local after all. – Aran-Fey Jul 23 '18 at 10:35
  • Yeah, that makes sense (in what I linked, the solution is to hijack the function's `return` call, best I can tell). I suppose I'm not married to a decorator implementation -- something like `my_instance.debug()` would also be fine. I'll edit the answer accordingly. – Soul Donut Jul 23 '18 at 11:40

0 Answers0