[Dev] Fix __repr__() errors in REPL when referencing an instance of a class & catch Exception #5794

Merged
Kreusada merged 2 commits from patch-104 into V3/develop 2022-08-23 02:32:03 +02:00
Kreusada commented 2022-07-04 01:41:19 +02:00 (Migrated from github.com)

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

### 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: ```py 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: ```py 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
Flame442 (Migrated from github.com) requested changes 2022-08-23 00:09:46 +02:00
@ -297,3 +296,4 @@
except Exception:
value = stdout.getvalue()
msg = "{}{}".format(value, traceback.format_exc())
else:
Flame442 (Migrated from github.com) commented 2022-08-23 00:09:40 +02:00

If this is the way this is handled (and there isn't some other part of the code that can be changed to address this issue), this should at least be catching the actual error, rather than a bare except.

If this is the way this is handled (and there isn't some other part of the code that can be changed to address this issue), this should *at least* be catching the actual error, rather than a bare `except`.
Kreusada (Migrated from github.com) reviewed 2022-08-23 02:10:01 +02:00
@ -297,3 +296,4 @@
except Exception:
value = stdout.getvalue()
msg = "{}{}".format(value, traceback.format_exc())
else:
Kreusada (Migrated from github.com) commented 2022-08-23 02:10:00 +02:00

I had left this except bare because the error being raised in __repr__() could be any exception. This is also the place where the value from __repr__() is formatted so that's why the issue is being addressed here.

I had left this except bare because the error being raised in `__repr__()` could be any exception. This is also the place where the value from `__repr__()` is formatted so that's why the issue is being addressed here.
Flame442 (Migrated from github.com) reviewed 2022-08-23 02:11:42 +02:00
@ -297,3 +296,4 @@
except Exception:
value = stdout.getvalue()
msg = "{}{}".format(value, traceback.format_exc())
else:
Flame442 (Migrated from github.com) commented 2022-08-23 02:11:42 +02:00

It should at least be except Exception in that case, as to not catch KeyboardInterrupt and other BaseException exceptions and prevent the bot from exiting as expected.

It should at least be `except Exception` in that case, as to not catch `KeyboardInterrupt` and other `BaseException` exceptions and prevent the bot from exiting as expected.
Flame442 (Migrated from github.com) approved these changes 2022-08-23 02:31:41 +02:00
Flame442 (Migrated from github.com) left a comment

That works, thanks!

That works, thanks!
red-githubbot[bot] commented 2023-04-19 23:56:45 +02:00 (Migrated from github.com)

#6065 is a backport of this pull request to Red 3.4.

#6065 is a backport of this pull request to [Red 3.4](https://github.com/Cog-Creators/Red-DiscordBot/tree/3.4).
Sign in to join this conversation.
No reviewers
No labels
Automated PR
Blocked
Blocked By: Damage Control
Blocked By: Dependency
Blocked By: Other PR
Breaking Change
Category: CI
Category: Cogs - Admin
Category: Cogs - Alias
Category: Cogs - Audio
Category: Cogs - Bank
Category: Cogs - Cleanup
Category: Cogs - CustomCommands
Category: Cogs - Dev
Category: Cogs - Downloader
Category: Cogs - Economy
Category: Cogs - Filter
Category: Cogs - General
Category: Cogs - Image
Category: Cogs - Mod
Category: Cogs - Modlog
Category: Cogs - Mutes
Category: Cogs - Permissions
Category: Cogs - Reports
Category: Cogs - Streams
Category: Cogs - Trivia
Category: Cogs - Trivia - Lists
Category: Cogs - Warnings
Category: Core - API - App Commands Package
Category: Core - API - Audio
Category: Core - API - Bank
Category: Core - API - Commands Package
Category: Core - API - Config
Category: Core - API - Other
Category: Core - API - Utils Package
Category: Core - Bot Class
Category: Core - Bot Commands
Category: Core - Command-line Interfaces
Category: Core - Downloader
Category: Core - Help
Category: Core - i18n
Category: Core - Modlog
Category: Core - Other Internals
Category: Core - RPC/ZMQ
Category: Docker
Category: Docs - Changelogs
Category: Docs - For Developers
Category: Docs - Install Guides
Category: Docs - Other
Category: Docs - User Guides
Category: Meta
Category: RPC/ZMQ methods
Category: Vendored Packages
Changelog Entry: Added
Changelog Entry: Pending
Changelog Entry: Skipped
Closed: Duplicate
Closed: External
Closed: Invalid
Closed: User Error
Closed: Won't Fix
Complex Issue
Docs-only
Feature Branch
Good First Issue
Help Wanted
High Priority
Needs Backport To stable-docs
No Activity
No Repro
QA: Bypassed
QA: Changes Requested
QA: Passed
Release Blocker
Status: Accepted
Status: Frozen
Status: In Progress
Status: Needs Discussion
Status: Needs Info
Status: Needs Triage
Status: PRs Welcome
Type: Bug
Type: Dependency Update
Type: Deprecation
Type: Enhancement
Type: Feature
Type: Informational
Type: Merge
Type: Optimisation
Type: Question
Type: Removal
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
Mrcoolgamer11/Red-DiscordBot!5794
No description provided.