I’m encountering an issue with my Python code using Pyright type checker, specifically when I try to remove Any from the return type declaration.
I have this Python code where I encounter an error if I remove Any from the return type declaration.
Error message:
Function with declared return type "int" must return value on all code paths. "None" is incompatible with "int".
Now every single path returns an int at some point, is this a bug or I just have to use the Union thing as a python thing.
from dataclasses import dataclass
from typing import Any, Union, List
@dataclass
class IntOrString:
I: Union[int, None] = None
S: Union[str, None] = None
def funny_sum(xs: List[IntOrString]) -> int | Any:
if not xs:
return 0
head, *tail = xs
match head:
case IntOrString(I=i) if i is not None:
return i + funny_sum(tail)
case IntOrString(S=s) if s is not None:
return len(s) + funny_sum(tail)
xs = [IntOrString(I=1), IntOrString(S="hello"), IntOrString(I=3), IntOrString(S="world")]
# Output will be 1 + 5 + 3 + 5 = 14
result = funny_sum(xs)
Error
def funny_sum(xs: List[IntOrString]) -> int: { ... }
In Swift, enums support pattern matching, and this code would work fine. Does this mean that data classes in Python do not support pattern matching?
I appreciate any advice on resolving this issue with the return type declaration in Python.