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

Fix cross-variable type-narrowing example #17488

Merged
merged 1 commit into from
Jul 6, 2024
Merged

Fix cross-variable type-narrowing example #17488

merged 1 commit into from
Jul 6, 2024

Conversation

InSyncWithFoo
Copy link
Contributor

From Type narrowing § Limitations:

def f(a: str | None, b: str | None) -> str:
    if a is not None or b is not None:
        return a or b  # Incompatible return value type (got "str | None", expected "str")
    return 'spam'

A trivial counter-example is f('', None), which returns None. Ironically, this somewhat makes Mypy's diagnostic "correct".

I propose that str be replaced with a custom class C whose __bool__() is not defined (does it have to be @final too?):

class C:
    pass

def f(a: C | None, b: C | None) -> C:
    if a is not None or b is not None:
        return a or b  # Incompatible return value type (got "C | None", expected "C")
    return C()

Copy link
Collaborator

@hauntsaninja hauntsaninja left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for fixing!

@hauntsaninja hauntsaninja merged commit 4ccf216 into python:master Jul 6, 2024
2 checks passed
@InSyncWithFoo InSyncWithFoo deleted the type-narrowing-example branch July 6, 2024 20:52
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.

2 participants