Last active
July 24, 2017 18:33
-
-
Save SimplyAhmazing/bf209246af9f63cbe4ecfabe0514fe33 to your computer and use it in GitHub Desktop.
Track call depth of a method relative to other methods in a class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import inspect | |
def call_depth(instance): | |
methods_to_consider = [ | |
func_name | |
for func_name, _ in inspect.getmembers( | |
instance, predicate=inspect.ismethod) | |
] | |
stack_funcs = [i.function for i in inspect.stack()] | |
func_name = stack_funcs[1] | |
valid_call_stack = [] | |
for fn in stack_funcs[::-1]: | |
if fn in methods_to_consider: | |
valid_call_stack.append(fn) | |
return valid_call_stack.index(func_name) | |
class Foo(object): | |
def a(self): | |
print((call_depth(self) * '*') + 'a called..') | |
self.b() | |
def b(self): | |
print((call_depth(self) * '*') + 'b called..') | |
self.c() | |
def d(self): | |
print((call_depth(self) * '*') + 'd called..') | |
def c(self): | |
print((call_depth(self) * '*') + 'c called..') | |
self.d() | |
def start(self): | |
print((call_depth(self) * '*') + '"start" called..') | |
self.a() | |
Foo().start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: