Skip to content

Instantly share code, notes, and snippets.

@SimplyAhmazing
Last active July 24, 2017 18:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SimplyAhmazing/bf209246af9f63cbe4ecfabe0514fe33 to your computer and use it in GitHub Desktop.
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
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()
@SimplyAhmazing
Copy link
Author

Output:

"start" called..
*a called..
**b called..
***c called..
****d called..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment