Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BaseException lacks __new__() #12231

Closed
finite-state-machine opened this issue Jun 28, 2024 · 2 comments · Fixed by #12346
Closed

BaseException lacks __new__() #12231

finite-state-machine opened this issue Jun 28, 2024 · 2 comments · Fixed by #12346
Labels
stubs: false positive Type checkers report false errors

Comments

@finite-state-machine
Copy link

Summary

When overriding __new__() in a BaseException subclass, a call of form super().__new__(cls, arg0, [arg1, [arg2, ...]]]) causes type checkers to complain about unused positional argument(s), even though the positional args are both accepted and used by BaseException.__new__() — they become <BaseException>.args.

Root cause: type checkers believe super().__new__(...) in this context is a call to object.__new__(), rather than BaseException.__new__().

Proposed fix: typeshed should include a definition for BaseException.__new__() analogous to and compatible with to its existing signature for BaseException.__init__():

class BaseException:
    ...
    def __init__(self, *args: object) -> None: ...
    ...

Concrete example

Analyzing the following code....

from __future__ import annotations

class SomeException(Exception):

    def __new__(cls, alfa: str, bravo: str) -> SomeException:

        msg = f"{alfa} ({bravo})"
        return super().__new__(cls, msg)  # ᐊ── errors occur here

    def __init__(self, alfa: str, bravo: str):

        # (preserve these as attributes)
        pass

...with mypy causes this report:

bug.py|8| error: Too many arguments for "__new__" of "object"  [call-arg]
|| Found 1 error in 1 file (checked 1 source file)

...while pyright (without strict) says:

|| .../bug.py
bug.py|8| 37 - error: Expected 1 positional argument (reportCallIssue)
|| 1 error, 0 warnings, 0 informations 
@srittau srittau added the stubs: false positive Type checkers report false errors label Jul 12, 2024
@srittau
Copy link
Collaborator

srittau commented Jul 12, 2024

Our stubs are indeed missing BaseException.__new__, although it exists at runtime:

https://github.com/python/cpython/blob/65fededf9cc1780d5edbef8a6e0a7cf9bc15aea6/Objects/exceptions.c#L522

PR welcome!

@finite-state-machine
Copy link
Author

Thanks for this fix, @srittau!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
stubs: false positive Type checkers report false errors
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants