Skip to content

Instantly share code, notes, and snippets.

@pedrovhb
Created August 16, 2023 22:28
Show Gist options
  • Save pedrovhb/21170786310827e0b101356c7397e37d to your computer and use it in GitHub Desktop.
Save pedrovhb/21170786310827e0b101356c7397e37d to your computer and use it in GitHub Desktop.
A metaclass and base class which, when inherited from, enables @Snoop on all methods automagically
import inspect
from typing import Dict, Any
import snoop
snoop.install(columns=())
class _SnoopMeta(type):
def __new__(mcs, name: str, bases: tuple, dct: Dict[str, Any]) -> Any:
for key, value in dct.items():
if inspect.isfunction(value) and not inspect.iscoroutinefunction(value):
dct[key] = snoop(value)
return super().__new__(mcs, name, bases, dct)
# Base class for all classes that should have snooping enabled
class SnoopBase(metaclass=_SnoopMeta):
pass
if __name__ == '__main__':
class Foo(SnoopBase):
def bar_the_foo(self, foo: int) -> float:
x = 0
for i in range(10):
x = foo ** (i/foo)
if x + 1 > 10:
break
return x
Foo().bar_the_foo(3)
"""
Snoop line-by-line:
>>> Call to Foo.bar_the_foo in File ".../scratch_5.py", line 25
.............. self = <__main__.Foo object at 0x7fd6d1ac6650>
.............. foo = 3
25 | def bar_the_foo(self, foo: int) -> float:
26 | x = 0
27 | for i in range(10):
.................. i = 0
28 | x = foo ** (i/foo)
...................... x = 1.0
29 | if x + 1 > 10:
27 | for i in range(10):
.................. i = 1
28 | x = foo ** (i/foo)
...................... x = 1.4422495703074083
29 | if x + 1 > 10:
27 | for i in range(10):
.................. i = 2
28 | x = foo ** (i/foo)
...................... x = 2.080083823051904
29 | if x + 1 > 10:
27 | for i in range(10):
.................. i = 3
28 | x = foo ** (i/foo)
...................... x = 3.0
29 | if x + 1 > 10:
27 | for i in range(10):
.................. i = 4
28 | x = foo ** (i/foo)
...................... x = 4.3267487109222245
29 | if x + 1 > 10:
27 | for i in range(10):
.................. i = 5
28 | x = foo ** (i/foo)
...................... x = 6.240251469155713
29 | if x + 1 > 10:
27 | for i in range(10):
.................. i = 6
28 | x = foo ** (i/foo)
...................... x = 9.0
29 | if x + 1 > 10:
27 | for i in range(10):
.................. i = 7
28 | x = foo ** (i/foo)
...................... x = 12.980246132766677
29 | if x + 1 > 10:
30 | break
31 | return x
<<< Return value from Foo.bar_the_foo: 12.980246132766677
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment