flupy icon indicating copy to clipboard operation
flupy copied to clipboard

filter does not work with type guards

Open scarf005 opened this issue 2 years ago • 1 comments

Summary

python 3.10 introduced type guards similar to that of typescript. however, flupy does not seem to support this feature.

image

from typing import Any, TypedDict, TypeGuard

from flupy import flu


class Person(TypedDict):
    name: str
    age: int


def is_person(val: Any) -> TypeGuard[Person]:
    try:
        return (
            isinstance(val, dict)
            and isinstance(val["name"], str)
            and isinstance(val["age"], int)
        )
    except KeyError:
        return False


def get_age(val: Person):
    return f"Age: {val['age']}"


result = (
    flu([Person(name="Alice", age=20), 3, "afds", {"name": "Eve"}])
    .filter(is_person)
    .map(get_age)
    .collect()
)

scarf005 avatar Mar 26 '23 06:03 scarf005

By the strictest definition, filter should not have any impact on the underlying elements but I think this is a good exception.

def filter(self, func: Callable[..., bool], *args: Any, **kwargs: Any) -> "Fluent[T]"

I'm not current on the latest enhancements to mypy but I'd be happy to accept a PR if you're interested in tinkering with the implementation of filter to support that use case?

olirice avatar Mar 27 '23 14:03 olirice