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

Custom type narrowing with a special decorator #7870

Closed
wants to merge 7 commits into from

Conversation

gantsevdenis
Copy link
Contributor

@gantsevdenis gantsevdenis commented Nov 4, 2019

This is surely not meant to be merged.. but just a small proposal?
I think the narrow_cast (or whatever it's called) should be inside typing and not mypy.
Having that decorator, type narrowing with user-defined functions is trivial (cf tests) and looks something like

@narrow_cast(str)  # mypy will narrow type to 'str' if this returns True
def is_fizz_buzz(foo):
    return foo in ['fizz', 'buzz']

def foobar(foo: Union[str, float]):
    if foo in ['fizz', 'buzz']:
        reveal_type(foo)  # N: Revealed type is 'Union[builtins.str, builtins.float]'
    if is_fizz_buzz(foo):
        reveal_type(foo)  # N: Revealed type is 'builtins.str'

@ilevkivskyi
Copy link
Member

This looks too ad-hoc TBH. I would rather implement support for type-guards using overloads, see #4063 and #5206. This will not require any new special forms and will be more flexible.

@DustinWehr
Copy link

@ilevkivskyi so is your concern that a more-general feature that comes later (but how much later?) would make this (seemingly) simple one obsolete? That doesn't seem like a big deal, especially if the documentation for @narrow_cast expressed that expectation, or if we later provided a little converter script that converts source code containing @narrow_cast to use the more-general mechanism.

@gantsevdenis if you got this working, I'd be interested enough to help maintain a fork.

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

Successfully merging this pull request may close these issues.

3 participants