Skip to content

Provide decorator for unsafe overrides #5704

@JukkaL

Description

@JukkaL

Unsafe overrides are pretty common when annotating legacy codebases. The recommended way to deal with this is to add a # type: ignore comment. This has a few major issues, though:

  1. It's not intuitive. Users often don't realize that they should use it in cases like this.
  2. Users frequently misunderstand # type: ignore and believe that it ignores the type annotation, even though it only ignores the error message.
  3. Users are sometimes confused about the line on which the comment should be placed. Also, it may be unclear what to do if there is an existing comment on the line.
  4. Some users don't like to litter their code with magic comments.
  5. A # type: ignore can ignore unrelated errors that the user doesn't want to be ignored.

I propose to add a decorator that can be used to silence this error, and only this error. Example:

from mypy_extensions import unsafe_override

class Result: ...

class Thing:
    @unsafe_override
    def __eq__(self, other: object) -> Result:  # Result is an unsafe return type
        # ... omitted

This would have these benefits:

  • There is less room for misunderstanding, since the decorator is explicit about what it's used for.
  • It's easier to use, since it doesn't have to be on a specific line.
  • It doesn't look as magical/messy as a magic comment.
  • It only ignores this specific error condition, so it won't hide unrelated errors.
  • It would be easy to Google documentation for the decorator when reading code. Documentation can be explicit about why and when this should be used and provide extended discussion.

See #2783 and #1237 for relevant previous discussions.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions