Skip to content

Returning optional union from method complains about got "object" #12823

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
Garrett-R opened this issue May 20, 2022 · 3 comments
Closed

Returning optional union from method complains about got "object" #12823

Garrett-R opened this issue May 20, 2022 · 3 comments
Labels
bug mypy got something wrong topic-join-v-union Using join vs. using unions topic-type-context Type context / bidirectional inference

Comments

@Garrett-R
Copy link

Bug Report

Mypy thinks my method returns "object" which is not right.

To Reproduce

Run Mypy on this file:

from typing import Optional


class Cat:
    pass


class Dog:
    pass


class MyClass:
    def __init__(self) -> None:
        self.pet: Optional[Dog | Cat] = None

    def get_pet(self) -> Optional[Dog | Cat]:
        if input() == 'yes':
            self.pet = Cat()
        else:
            self.pet = Dog()
        return self.pet  # (incorrect Mypy error on this line!)

Expected Behavior

This should have no errors.

Actual Behavior

It yields:

error: Incompatible return value type (got "object", expected "Union[Dog, Cat, None]")

Your Environment

  • Mypy version used: v0.950
  • Mypy command-line flags: none
  • Mypy configuration options: none
  • Python version used: 3.10.4
  • Operating system and version: Ubuntu 20.04
@Garrett-R Garrett-R added the bug mypy got something wrong label May 20, 2022
@erictraut
Copy link

Looks like another case where a false positive results from using a join operation rather than a union.

@JelleZijlstra JelleZijlstra added the topic-join-v-union Using join vs. using unions label May 20, 2022
@hauntsaninja hauntsaninja added the topic-type-context Type context / bidirectional inference label May 22, 2022
@hauntsaninja
Copy link
Collaborator

Note the following works:

    def get_pet(self) -> Dog | Cat | None:
        pet: Dog | Cat | None = None
        if input() == 'yes':
            pet = Cat()
        else:
            pet = Dog()
        return pet

Looks like we're losing the type context of the instance variable.

@sterliakov
Copy link
Collaborator

Fixed in #18538 and passes on current master.

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 topic-type-context Type context / bidirectional inference
Projects
None yet
Development

No branches or pull requests

5 participants