8000 Function to narrow types · Issue #12177 · python/mypy · GitHub
[go: up one dir, main page]

Skip to content

Function to narrow types #12177

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

Closed
Dreamsorcerer opened this issue Feb 14, 2022 · 2 comments
Closed

Function to narrow types #12177

Dreamsorcerer opened this issue Feb 14, 2022 · 2 comments
Labels

Comments

@Dreamsorcerer
Copy link
Contributor

Feature

A function, similar to cast(), which narrows a type from a union by including or excluding types.

Pitch

Often I encounter code where I know the type better than mypy. For example, a function that may return None or Any in some circumstances:

m = re.search("foo (.*)", some_string)
result = m.group(0)

This results in errors about Any, which then requires me to do cast(str, m.group(0)). But, if I make a mistake (str instead of bytes) or the types change in future, then I will miss a type error, as cast() completely overrules the type.

If instead, we could say "this is not X", then this would be a lot safer. e.g. Something like exclude(Any, m.group(0)) would ensure that any changes to the types are still reflected in the resulting type, and can also produce an error if the excluded type is no longer in the union type, thus ensuring that the code always stays relevant.

Alternatively, it could work as an include, saying what the type is, but also requiring the original type to be a superset of this. The cast() function could even be reused for this, with something like cast(str, m.group(0), narrow=True).

@JelleZijlstra
Copy link
Member

Similar to #941 and #5687 (comment).

@Dreamsorcerer
Copy link
Contributor Author

Perfect, 6373 thanks. That one was tricky to search for.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants
0