11

I implemented my own __getattr__() to loosely handle any non-existent attributes.

I just so happened to define this class in a Jupyter notebook to experiment with it interactively.

IPython creates _ipython_canary_method_should_not_exist_ due to this __getattr__ implementation – and I'd like to understand what this is and how to "clean it up" is possible.

There is this issue opened about it, but it's not clear to my why – if it checks for permissive handling within __getattr__ – it doesn't check to see that _repr_html_ is implemented in the OP's example?

from types import SimpleNamespace

class Metabox(SimpleNamespace):

    def __getattr__(self, name):
        """
        Create a new namespace for any non-existing attributes.
        """
        print("calling __getattr__")
        self.__dict__[name] = Metabox()
        return self.__dict__[name]
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
conner.xyz
  • 6,273
  • 8
  • 39
  • 65
  • 1
    It maybe caused by ipython trying to test if an instance `a` of your class `hasattr(a, '_ipython_canary_method_should_not_exist_')`, and `hasattr` [by default](https://docs.python.org/3/library/functions.html#hasattr) called `__getattr__`. – taper May 14 '19 at 08:09

1 Answers1

10

As taper mentioned in above comments; IPython sometimes needs to inspect objects to know whether they have some methods.

To handle object like yours; that always say "yes", when we have doubt we probe for this name; and if the object says "yep, I got that !" we know the object lies and implemented a __getattr__.

conner.xyz
  • 6,273
  • 8
  • 39
  • 65
Matt
  • 27,170
  • 6
  • 80
  • 74