Skip to content

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

Description

@Garrett-R

Bug Report

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

To Reproduce

Run Mypy on this file:

fromtypingimportOptionalclassCat:
passclassDog:
passclassMyClass:
def__init__(self) ->None:
self.pet: Optional[Dog|Cat] =Nonedefget_pet(self) ->Optional[Dog|Cat]:
ifinput() =='yes':
self.pet=Cat()
else:
self.pet=Dog()
returnself.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