Skip to content

Function to narrow types #12177

Closed
Closed
@Dreamsorcerer

Description

@Dreamsorcerer

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).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions