2020-12-30

How do you watch a callable object's arguments and return values?

I have a Python object and I want to know what args, kwargs, and return values it made. The solution should be something like this.


class Fizz(object):
    def do_something(self, item, blah=8):
        return "done"


buzz = Fizz()

with watch(buzz.do_something) as container:
    buzz.do_something("asdf")
    buzz.do_something("another", blah=10)

container  # [(("asdf", ), dict(), "done"), (("another", ), {"blah": 10}, "done")]

So the key points are

  • Able to watch args, kwargs, and return values
  • Is temporary (I can decide when and how to watch and when to un-watch)
  • Ideally, this should work with instance objects. But at minimum, it needs to be able to at least work with class, method, and function definitions (like how mock.patch does it).

Similar Things That Already Exist

mock.patch allows you to watch arguments but, as far as I know, it replaces the class / function / method. The original callable object does not get called, which is not what I want. I want the original to still be called while also keeping track of what's passed in and out of the callable object.

Maybe there's a way to make mock do what I need it to do or some other existing library? Anyone know of anything?



from Recent Questions - Stack Overflow https://ift.tt/3mWUgFJ
https://ift.tt/eA8V8J

No comments:

Post a Comment