X Tutup
The Wayback Machine - https://web.archive.org/web/20201019100850/https://github.com/python/typing/issues/703
Skip to content
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

Assertion and checking functions #703

Open
srittau opened this issue Feb 19, 2020 · 2 comments
Open

Assertion and checking functions #703

srittau opened this issue Feb 19, 2020 · 2 comments

Comments

@srittau
Copy link
Contributor

@srittau srittau commented Feb 19, 2020

I'll just leave this here for potential future consideration as it came up on gitter's typing-dev channel. Typescript has something called assertion functions, which enables the type checker to understand that a function does not return if a certain condition is false. I think something similar, but more generalized, would be interesting, especially for unit test functions like assert_is_instance(), assert_true() etc.

def assert_positive(x: object) -> AssertsInstance["x", int]:
    assert isinstance(x, int) and x > 0

Related, checking functions could work like this:

def is_positive(x: object) -> ChecksInstance["x", int]:
    return isinstance(x, int) and x > 0

def my_func(x: Union[int, str]) -> None:
    if is_positive(x):
        # x must be an int
        ...
    else:
        # x can be an int or str
        ...
@TeamSpen210
Copy link

@TeamSpen210 TeamSpen210 commented Feb 20, 2020

This is already possible with overload and Literal, though I don't think any type checkers can take advantage of this information yet.

@overload
def assert_positive(x: int) -> bool: ...
@overload
def assert_positive(x: object) -> NoReturn: ...

@overload
def is_positive(x: int) -> Literal[True]: ...
@overload
def is_positive(x: object) -> Literal[False]: ...
@srittau
Copy link
Contributor Author

@srittau srittau commented Feb 20, 2020

That is a clever trick that works for some functions like assert_is_instance(), but in the examples given it does not work, since it ignores the non-type check part. Another example is type narrowing, based on object fields:

class Proto(Protocol): ...
class SubProto(Proto):
    sub_field: int

class MyClass: # implements protocol SubProto
    sub_field = 42

def is_sub_proto(o: Proto) -> ChecksInstance["o", SubProto]:
    return hasattr(o, "sub_field")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
2 participants
You can’t perform that action at this time.
X Tutup