Skip to content

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

Closed

Description

@Garrett-R

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

Activity

  1. erictraut commented on May 20, 2022

    @erictraut

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

  2. hauntsaninja commented on May 22, 2022

    @hauntsaninja
    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.

  3. sterliakov commented on Mar 28, 2025

    @sterliakov
    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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-join-v-unionUsing join vs. using unionstopic-type-contextType context / bidirectional inference

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions