Asserting Type Guards that works with mypy ? #1527
tushar5526
started this conversation in
General
Replies: 1 comment 1 reply
-
There is currently no support in the Python type system for a "type assert". Other languages like TypeScript have this sort of feature. There was some discussion of adding a If you're able to modify the code in question, you can change the "check" function to return the value if its type matches and raise an error if not. from typing import Any, Literal, TypeVar, overload
T = TypeVar("T")
@overload
def check_obj_of_type(
obj: Any, validation_type: type[T], raise_error: Literal[True]
) -> T:
...
@overload
def check_obj_of_type(
obj: Any, validation_type: type[T], raise_error: bool = False
) -> Any:
...
def check_obj_of_type(
obj: Any, validation_type: type[T], raise_error: bool = False
) -> T | Any:
if isinstance(obj, validation_type):
return obj
if raise_error:
raise TypeError(f"Object should be {validation_type} not '{type(obj)}'")
return False
class SomeType:
...
class SomeClass:
some_var: Any
def do_some_stuff(self) -> SomeType:
return check_obj_of_type(self.some_var, SomeType, raise_error=True) |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I am not sure if this is the right place to ask this question, but I have been bugged with a simple
typing
problem of needing a behaviour where I can have something like an "asserting"TypeGuard
that works with mypy.If I want to use
check_obj_of_type
with say a function likemypy
will error out for the above code statingMissing return statement
but in-fact the code will never reach theelse
clause.For
mypy
to pass successfully, one would have to either#type ignore[return]
or add a an assert inelse
clause. Is there any other better way to do this ?Beta Was this translation helpful? Give feedback.
All reactions