Red-DiscordBot icon indicating copy to clipboard operation
Red-DiscordBot copied to clipboard

[Dev] Fix `__repr__()` errors in REPL when referencing an instance of a class

Open Kreusada opened this issue 3 years ago • 0 comments

Description of the changes

I have noticed that when __repr__() is to raise an exception, the [p]repl command fails, and the exception is explicitly raised instead of being sent as a message in the session. However, this only happens when the instance is referenced (object()) and not when the repr() function is used (repr(object())).

Take the following code, for example:

class A(object):
    def __repr__(self) -> str:
        raise Exception

If we were to type A(), Exception would be explicitly raised as a command error. However, typing repr(A()) would behave as you would expect.

I discovered this with my own code in a REPL session:

def __repr__(self) -> str:
    attrs = {n[1:]: getattr(self, n) for n in self.__slots__}
    join = ", ".join(f"{k}={v!r}" for k, v in attrs.items())
    return f"{self.__class__.__name__}({join})"

I had not included the __slots__ definition within the class, hence why an AttributeError was raised when I typed "MyClass()". I was expecting this error to be printed in the session's channel, not to error the command.

Have the changes in this PR been tested?

Yes, working

Kreusada avatar Jul 03 '22 23:07 Kreusada