Skip to content

Fixes raise CustomError creationg with __init__ with arguments #11125

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

Merged
merged 4 commits into from
Sep 17, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -3424,6 +3424,10 @@ def type_check_raise(self, e: Expression, s: RaiseStmt,
expected_type.items.append(TupleType([any_type, any_type, any_type], tuple_type))
self.check_subtype(typ, expected_type, s, message_registry.INVALID_EXCEPTION)

if isinstance(typ, FunctionLike):
# https://github.com/python/mypy/issues/11089
self.expr_checker.check_call(typ, [], [], e)

def visit_try_stmt(self, s: TryStmt) -> None:
"""Type check a try statement."""
# Our enclosing frame will get the result if the try/except falls through.
Expand Down
30 changes: 28 additions & 2 deletions test-data/unit/check-statements.test
Original file line number Diff line number Diff line change
Expand Up @@ -406,8 +406,7 @@ class MyError(BaseException): pass
[out]
main:5: error: Exception must be derived from BaseException

[case testRaiseClassobject]
import typing
[case testRaiseClassObject]
class A: pass
class MyError(BaseException): pass
def f(): pass
Expand All @@ -418,6 +417,33 @@ raise object # E: Exception must be derived from BaseException
raise f # E: Exception must be derived from BaseException
[builtins fixtures/exception.pyi]

[case testRaiseClassObjectCustomInit]
class MyBaseError(BaseException):
def __init__(self, required) -> None:
...
class MyError(Exception):
def __init__(self, required1, required2) -> None:
...
class MyKwError(Exception):
def __init__(self, *, kwonly) -> None:
...
class MyErrorWithDefault(Exception):
def __init__(self, optional=1) -> None:
...
raise BaseException
raise Exception
raise BaseException(1)
raise Exception(2)
raise MyBaseError(4)
raise MyError(5, 6)
raise MyKwError(kwonly=7)
raise MyErrorWithDefault(8)
raise MyErrorWithDefault
raise MyBaseError # E: Too few arguments for "MyBaseError"
raise MyError # E: Too few arguments for "MyError"
raise MyKwError # E: Missing named argument "kwonly" for "MyKwError"
[builtins fixtures/exception.pyi]

[case testRaiseExceptionType]
import typing
x = None # type: typing.Type[BaseException]
Expand Down