Skip to content

Cannot assign an Optional[float] to a float #10340

Description

@fpdotmonkey

I have the class below which can optionally take a tuple, which itself optionally has float members, so (1.0, 2.0), None, (1.0, None), etc are all valid inputs.

I do checking in the class to see if None has been input, and ignore the input in those cases, but mypy is saying Optional[float] and float are incompatible for these assignments.

How can I specify to mypy that I've done my due diligence in type checking the input?

# foo.py
from typing import Optional, Tuple


class Foo:
    def __init__(
        self, bounds: Optional[Tuple[Optional[float], Optional[float]]] = None
    ):
        self._lower_bound: float = float("-inf")
        self._upper_bound: float = float("inf")
        if bounds:
            if bounds[0]:
                self._lower_bound = bounds[0]
            if bounds[1]:
                self._upper_bound = bounds[1]


Foo((1, 2))
$ mypy foo.py
foo.py:12: error: Incompatible types in assignment (expression has type "Optional[float]", variable has type "float")
foo.py:14: error: Incompatible types in assignment (expression has type "Optional[float]", variable has type "float")
Found 2 errors in 1 file (checked 1 source file)

I'm running mypy 0.812 with Python 3.8.5

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions