-
-
Notifications
You must be signed in to change notification settings - Fork 120
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Pattern matching raises ParseError when using return type annotation #348
Comments
Gave me a headache while trying to understand pattern matching... |
@ArneBachmann Yeah, right now pattern-matching functions don't support type annotations. For just return type annotation, this is probably doable, though it'd be much harder to also support argument type annotation. |
This issue bit me as well. I figured out a manual way to get fully working type annotations into pattern-matching functions, so in principle it can be done, but I have not had a chance to determine how to patch the coconut compiler to automate this. First, consider the following re-write of @ArneBachmann's function def g(a is int, b is int):
# type: (int, int) -> int
return a + b
g(3, 2) # should pass typecheck
g(3, "this") # should NOT pass typecheck The coconut compiler currently strips out the However, if I manually put the type annotation back into the generated python code, we start to get somewhere: ...
# Compiled Coconut: -----------------------------------------------------------
def g(*_coconut_match_to_args, **_coconut_match_to_kwargs): # line 1
# type: (int, int) -> int
# ^^^^^^^ manually put that line in
_coconut_match_check = False # line 1
... Running mypy directly over the altered
The last line is the typecheck fail we're after. We just need to deal with the MatchError stuff to get rid of extraneous errors coming from coconut's internally-generated code. That turns out to be easy; all we have to do is toss in ...
_coconut_match_err.pattern = 'def g(a is int, b is int):' # type: ignore # line 1
_coconut_match_err.value = _coconut_match_to_args # type: ignore # line 1
... And now (again ignoring errors coming from
Exactly the behavior we want. The arguments are clearly being typechecked. It's easy enough to show the return type is being properly checked as well. One critical thing about the |
Should mention that this won't generally work with functions using |
It appears that some |
@ArneBachmann @penntaylor The proposed plan for adding type annotations to pattern-matching functions is to use the new |
@penntaylor Hmm... good point. You could definitely just write a def typedef(actual_func: S, typed_func: T) -> Union[T, S] = actual_func instead (and make |
@evhub I think the only general way to avoid multimethods' collapsing into loose Unions or untyped messes is to use |
|
This is now fully supported as of |
The text was updated successfully, but these errors were encountered: