Gere
Gere

Reputation: 12717

Watching which function is called in Python

What is the easiest way to record function calls for debugging in Python? I'm usually interested in particular functions or all functions from a given class. Or sometimes even all functions called on a particular object attribute. Seeing the call arguments would be useful, too.

I can imagine writing decorators for all that, but then I'd still have to modify the source code in different places. And writing a class decorator which modifies all methods isn't that straightforward.

Is there a solution where I don't have to modify my source code? Ideally something which doesn't slow down Python too much.

Upvotes: 2

Views: 934

Answers (2)

martineau
martineau

Reputation: 123541

You ought to be able to implement something that does what you want using either sys.setprofile() or perhaps sys.settrace(). They both let you define a function to be called when specific "events" occur, like function calls, and pass additional information to which can be used to to determine the function/method being called and examine its arguments.

If you look around, there's probably sample usage code to use as a good starting point.

Upvotes: 1

moonsly
moonsly

Reputation: 550

Except decorators, for Python >= 3.0 you could use new __getattribute__ method for a class, which will be called every time you call any method of the object. You could look through Lutz "Learning Python" chapters 31, 37 about it.

Upvotes: 1

Related Questions