Skip to content

Allow accessing __init__ on final classes and when __init__ is final #19035

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
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
20 changes: 11 additions & 9 deletions mypy/checkmember.py
Original file line number Diff line number Diff line change
Expand Up @@ -308,18 +308,21 @@ def report_missing_attribute(
def analyze_instance_member_access(
name: str, typ: Instance, mx: MemberContext, override_info: TypeInfo | None
) -> Type:
if name == "__init__" and not mx.is_super:
# Accessing __init__ in statically typed code would compromise
# type safety unless used via super().
mx.fail(message_registry.CANNOT_ACCESS_INIT)
return AnyType(TypeOfAny.from_error)

# The base object has an instance type.

info = typ.type
if override_info:
info = override_info

method = info.get_method(name)

if name == "__init__" and not mx.is_super and not info.is_final:
if not method or not method.is_final:
# Accessing __init__ in statically typed code would compromise
# type safety unless used via super() or the method/class is final.
mx.fail(message_registry.CANNOT_ACCESS_INIT)
return AnyType(TypeOfAny.from_error)

# The base object has an instance type.

if (
state.find_occurrences
and info.name == state.find_occurrences[0]
Expand All @@ -329,7 +332,6 @@ def analyze_instance_member_access(
mx.msg.note("Occurrence of '{}.{}'".format(*state.find_occurrences), mx.context)

# Look up the member. First look up the method dictionary.
method = info.get_method(name)
if method and not isinstance(method, Decorator):
if mx.is_super and not mx.suppress_errors:
validate_super_call(method, mx)
Expand Down
21 changes: 21 additions & 0 deletions test-data/unit/check-final.test
Original file line number Diff line number Diff line change
Expand Up @@ -1229,3 +1229,24 @@ reveal_type(B() and 42) # N: Revealed type is "Literal[42]?"
reveal_type(C() and 42) # N: Revealed type is "__main__.C"

[builtins fixtures/bool.pyi]

[case testCanAccessFinalClassInit]
from typing import final

@final
class FinalClass:
pass

def check_final_class() -> None:
new_instance = FinalClass()
new_instance.__init__()

class FinalInit:
@final
def __init__(self) -> None:
pass

def check_final_init() -> None:
new_instance = FinalInit()
new_instance.__init__()
[builtins fixtures/tuple.pyi]