Skip to content

Type of conditional expression is object when using Protocol #11722

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
carlosporta opened this issue Dec 12, 2021 · 1 comment
Closed

Type of conditional expression is object when using Protocol #11722

carlosporta opened this issue Dec 12, 2021 · 1 comment
Labels
bug mypy got something wrong topic-join-v-union Using join vs. using unions topic-ternary-expression a if b else c

Comments

@carlosporta
Copy link

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()
@carlosporta carlosporta added the bug mypy got something wrong label Dec 12, 2021
@JelleZijlstra JelleZijlstra added the topic-join-v-union Using join vs. using unions label Mar 21, 2022
@hauntsaninja
Copy link
Collaborator

Fixed by #17427

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-join-v-union Using join vs. using unions topic-ternary-expression a if b else c
Projects
None yet
Development

No branches or pull requests

4 participants