-
from dataclasses import dataclass
@dataclass
class Row:
cell: str
@dataclass
class Table:
row: Row | None
def query(key: int) -> Table | None:
"""
The Table.row is optional somewhere else, however, in
this function, row is guaranteed to be not None when Table is not None.
Question: how to narrow the type of Table.row in this function?
"""
if key == 1:
return Table(
row=Row(cell="value"),
)
if table := query(1):
# there is `"cell" is not a known member of "None"` warning
print(table.row.cell) The Table.row is optional somewhere else, however, in this function, row is guaranteed to be not None when Table is not None. Question: how to narrow the type of Table.row in this function? |
Beta Was this translation helpful? Give feedback.
Answered by
erictraut
Jan 30, 2024
Replies: 1 comment 3 replies
-
If you're sure that if table := query(1):
assert table.row is not None
print(table.row.cell) |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
jackjyq
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you're sure that
table.row
is notNone
, you can add anassert
statement to this effect. This documents your assumption for yourself, other readers of your code, and for static type checkers.