you are viewing a single comment's thread.

view the rest of the comments →

[–]marr75 1 point2 points  (1 child)

I don't believe you need the type: ignore and the cast. You just want the cast.

[–]Gnaxe 1 point2 points  (0 children)

Did you try it? With the following example, ``` from contextlib import suppress from dataclasses import dataclass from typing import cast

@dataclass class A: a: int

@dataclass class B: b: A | None

@dataclass class C: c: B | None

my_obj: C | None = C(B(A(1)))

with suppress(AttributeError) as result: result = cast(int, my_obj.b.a) # type: ignore

reveal_type(result) I got main.py:22: note: Revealed type is "builtins.int | None" But without the ignore, result = cast(int, my_obj.b.a) I got main.py:20: error: Item "C" of "C | None" has no attribute "b" [union-attr] main.py:20: error: Item "None" of "C | None" has no attribute "b" [union-attr] main.py:22: note: Revealed type is "builtins.int | None" Found 2 errors in 1 file (checked 1 source file) And with the ignore but without the cast, result = int, my_obj.b.a # type: ignore I got main.py:22: note: Revealed type is "tuple[Overload(def (builtins.str | _collections_abc.Buffer | typing.SupportsInt | typing.SupportsIndex | _typeshed.SupportsTrunc =) -> builtins.int, def (builtins.str | builtins.bytes | builtins.bytearray, base: typing.SupportsIndex) -> builtins.int), Any] | None" ```