Skip to content

Instantly share code, notes, and snippets.

@ties
Last active June 13, 2017 13:58
Show Gist options
  • Select an option

  • Save ties/4ec4798f644e72aac1d5c49ab2428b54 to your computer and use it in GitHub Desktop.

Select an option

Save ties/4ec4798f644e72aac1d5c49ab2428b54 to your computer and use it in GitHub Desktop.
Utility that prints calls on the attribute path of the object
import logging
logging.basicConfig()
logging.getLogger(__name__).setLevel(logging.INFO)
LOG = logging.getLogger(__name__)
class PrintCalls(object):
"""
Log all the calls done on this object. This object wraps, and redirects
calls to the 'obj' parameter iff given to it's constructor.
>> # pseudo-docstring
>> a = PrintCalls()
>> a.foo()
INFO:__main__:<root>.foo((), {})
>> a.foo.bar()
INFO:__main__:<root.foo.bar((), {})
>> a.foo.bar.baz(1)
INFO:__main__:<root>.foo.bar.baz(1, {})
"""
def __init__(self, obj=None, label=tuple(['<root>'])):
self.label = label
self.obj = obj
def __call__(self, *args, **kwargs):
LOG.info('%s(%s, %s)', '.'.join(self.label),
', '.join(map(str, args)), kwargs)
if self.obj:
self.obj(*args, **kwargs)
def __getattr__(self, attr):
return PrintCalls(obj=getattr(self.obj, attr, None),
label=self.label + (attr,))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment