Skip to content

Type of conditional expression is object when using Protocol #11722

Closed
@carlosporta

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()

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions