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

Ternary expression of context managers is inferred as object #16055

Closed
ringohoffman opened this issue Sep 6, 2023 · 2 comments
Closed

Ternary expression of context managers is inferred as object #16055

ringohoffman opened this issue Sep 6, 2023 · 2 comments
Labels
bug mypy got something wrong topic-join-v-union Using join vs. using unions

Comments

@ringohoffman
Copy link

Related: #7738

A ternary expression of context managers is inferred as object, leading to an erroneous attr-defined errors about object not defining __enter__ and __exit__.

To Reproduce

class A:
    def __enter__(self) -> 'A':
        return self

    def __exit__(self, *args) -> None:
        pass

class B:
    def __enter__(self) -> 'B':
        return self

    def __exit__(self, *args) -> None:
        pass

def foo() -> bool:
    return True

a_or_b = A() if foo() else B()

reveal_type(a_or_b)  # Revealed type is "builtins.object"

with a_or_b:  # "object" has no attribute "__enter__" & "object" has no attribute "__exit__"
    ...

Gist URL: https://gist.github.com/mypy-play/8e363dcee24e9fab1c3abd89d1539635
Playground URL: https://mypy-play.net/?mypy=master&python=3.11&gist=8e363dcee24e9fab1c3abd89d1539635

Expected Behavior

I would expect that the type of "a_or_b" to be "A | B" and not raise an attr-defined error.

@ringohoffman ringohoffman added the bug mypy got something wrong label Sep 6, 2023
@erictraut
Copy link

This is because mypy uses a join operation rather than a union when unifying types. Here is the master bug for this issue, and you can search for all related issues using the topic-join-v-union tag.

@hauntsaninja
Copy link
Collaborator

Fixed in #17427

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-join-v-union Using join vs. using unions
Projects
None yet
Development

No branches or pull requests

4 participants