Skip to content

Type of conditional expression is object when using Protocol #11722

Description

@carlosporta

Mypy does not infer that a conditional expression returns a Protocol. Here is the code:

from typing import Protocol


class Shape(Protocol):
    def area(self) -> str:
        ...


class Circle:
    def area(self) -> str:
        return 'π * r²'


class Square:
    def area(self) -> str:
        return 'w * l'


class ShapeFactory:
    def create(self, shape_type: str) -> Shape:
        return Circle() if shape_type == 'circle' else Square()  # Here

Error message:

error: Incompatible return value type (got "object", expected "Shape")

But if I change it to an conditional statement it works perfectly:

# ... code omitted

class ShapeFactory:
    def create(self, shape_type: str) -> Shape:
        if shape_type == 'circle':
            return Circle()
        else:
            return Square()

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions