Let's say you have a particular method (function) from a particular module (of a particular class, optional). Is it possible via introspection of the library source code print all the lines where that method is called (used)? It can be called internally (with self.method_name()) or externally with (object1.method_name() in source file 1, object2.method_name() in source file 2, ... and objectN.method_name() in source file N).
An example could be shown on re
module and it's method re.findall
.
I tried to print the lines with grep
, but this is a problem for
methods having the same name (e.g. I tried it with method named connect(),
but 24 classes have a method named connect... I'd like to filter this for
particular class (and/or module).
I grep for function usage fairly regularly. Fortunately, I have never been interested in something that would be duplicated so heavily.
Here is what I might do, rather than write one-time code, if the false hits for Class.method
were too common to filter manually. First grep for class Class
to find the module
with the class definition and note the range of lines. Then grep that module for self.method
and delete or ignore hits outside that range. Then grep all modules of interest for import module
and from module
to find modules that might use the class and method. Then grep groups of modules depending on the specific form of import.
As others have pointed out, even this will miss calls that use aliases for the method name. But only you can know if this is an issue for your scenario. It is not, that I know of, for what I have done.
An entirely different approach, not depending on names, is to instrument the function with code that logs its calls, after using dynamic introspection to determine the caller. (I believe there are SO Q&As about this.)