mypy icon indicating copy to clipboard operation
mypy copied to clipboard

False Positive when remembering truthiness of a group of values

Open govindrai opened this issue 1 year ago • 0 comments

Bug Report This might be a tough one to support...MyPy doesn't understand that if a conditional check is done to determine if one value out of a group of values may be truthy, then when that same group is referenced later, the final result will also be truthy.

To Reproduce

Gist URL Playground URL

from dataclasses import dataclass
from typing import Optional

@dataclass
class InAppBrowserActionData:
    merchant_ari: str
    merchant_landing_url: str
    merchant_name: str
    public_api_key: str
    offer_ari: Optional[str] = None
    event_id: Optional[str] = None

@dataclass
class ActionItemCollectionRequestV2:
    merchant_ari: str
    item_url: Optional[str] = None
    affiliate_url: Optional[str] = None
    merchant_name: Optional[str] = None
    public_api_key: Optional[str] = None

    def get_action(self) -> Optional[InAppBrowserActionData]:
        if (
            (self.item_url or self.affiliate_url)
            and self.merchant_name
            and self.public_api_key
        ):
            return InAppBrowserActionData(
                merchant_ari=self.merchant_ari,
                public_api_key=self.public_api_key,
                merchant_landing_url=self.affiliate_url or self.item_url,
                merchant_name=self.merchant_name,
            )

        return None

Expected Behavior I expect there to be no error since one or both self.affiliate_url or self.item_url will end up being truthy as already verified by the if statement.

Actual Behavior

main.py:30: error: Argument "merchant_landing_url" to "InAppBrowserActionData" has incompatible type "Optional[str]"; expected "str"  [arg-type]

Your Environment

  • Mypy version used: 1.8.0
  • Python version used: 3.7

govindrai avatar Feb 16 '24 15:02 govindrai