Skip to content

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

Closed
@Garrett-R

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

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