question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Allow snooping on all methods of a class

See original GitHub issue

I didn’t find a way to easily snoop on all the methods of a class without adding the decorator to every single method. Below is an outline of a way to do it with a metaclass. There was an issue overwriting the magic/dunder methods (AttributeError: type object 'SnoopedMetaClass' has no attribute '__code__'), but for everything else it works fine.

import pysnooper

class SnoopMetaClass(type):
    """Converts every method to a snooped method"""
    def __new__(cls, name, bases, attrs, **kwargs):
        # Create the instance like normal
        instance = super().__new__(cls, name, bases, attrs)

        # If the class has a "snoop_kwargs" class attribute, get it here
        # so we can forward it to pysnooper.snoop. Set it to an empty dict by default.
        kwargs = attrs.get("snoop_kwargs", {})

        # Iterate over every attribute and find the ones that are methods
        for attr in dir(instance):
            # Certain magic methods do not like to be overridden by the snooped version
            if attr.startswith("__"):
                continue

            # Override the value with a snooped one if it is callable
            value = getattr(instance, attr)
            if callable(value):
                snooped = pysnooper.snoop(**kwargs)(value)
                setattr(instance, attr, snooped)
        return instance




class MyClass(metaclass=SnoopMetaClass):
    snoop_kwargs = {"output": "log.txt"}

   def __init__(self):
       """Will not be snooped on since it is a magic method"""

    def my_method(self):
        """Normal method, will be snooped on"""

    def my_other_method(self):
        """Normal method, will be snooped on"""

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
cool-RRcommented, Sep 8, 2019

This is a cute idea. My priority is to keep the interface as simple as possible, so if you’d like me to merge it, I’d like you to modify it so it’s a decorator on the class rather than a metaclass. Submit a PR like that, with tests and documentation, and I’ll likely merge it.

0reactions
alexmojakicommented, Sep 8, 2019

Another problem:

import pysnooper


@pysnooper.snoop()
class A:
    @pysnooper.snoop()
    def foo(self):
        pass


A().foo()

Output:

Source path:... /Users/alexhall/Desktop/python/snoop/venv/lib/python3.7/site-packages/pysnooper/tracer.py
Starting var:.. args = (<__main__.A object at 0x104f39b38>,)
Starting var:.. kwargs = {}
Starting var:.. function = <function A.foo at 0x105557950>
Starting var:.. self = <pysnooper.tracer.Tracer object at 0x104f39ac8>
21:27:56.248748 call       250         def simple_wrapper(*args, **kwargs):
21:27:56.255392 line       251             with self:
21:27:56.260776 line       252                 return function(*args, **kwargs)
    Source path:... /Users/alexhall/Library/Preferences/PyCharm2019.2/scratches/scratch_441.py
    Starting var:.. self = <__main__.A object at 0x104f39b38>
    21:27:56.262119 call         7     def foo(self):
    21:27:56.262523 line         8         pass
    21:27:56.262618 return       8         pass
    Return value:.. None
Call ended by exception
Read more comments on GitHub >

github_iconTop Results From Across the Web

Does any mocking framework allow spying on a super ...
Ok, my mock fu is still developing.. but the calls already has an overridden method with the same signature, that throws an exception...
Read more >
Allow spying on interfaces so that it is convenient to work ...
Imho spying an interface spy(Interface.class) is wrong, even when there's default methods, it doesn't feel like a a spy. As spy have more ......
Read more >
IP Multicast Routing Configuration Guide, Cisco IOS XE ...
Configuring IGMP Snooping. ... IP multicast traffic uses group addresses, which are Class D IP addresses. ... Setting the Snooping Method.
Read more >
What is DHCP Snooping? - Explanation and Configuration
DHCP snooping is a security feature on a Layer 2 network switch that can prevent unauthorized rogue DHCP servers from accessing your network....
Read more >
Understanding DHCP Snooping (ELS) | Junos OS
This topic includes information about enabling Dynamic Host Configuration Protocol ... When DHCP snooping is enabled for a VLAN, all DHCP packets sent...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found