mypy complains about missing attribute of object of type Optional even after checking that the argument is not None

I have a data class having as member a list of objects of another class having as member an object of type Optional[CustomType], and I need to call a method of CustomType class on that member, only when the member is not None.
Even if such check is explicitly performed, mypy still complains about the missing attribute of the item None of the CustomType | None union.

Here follows a working example using str as CustomType that highlights the issue:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>from dataclasses import dataclass
from typing import Optional
@dataclass(frozen=True)
class Sample:
tag: Optional[str] = None
@dataclass(frozen=True)
class Container:
samples: list[Sample]
if __name__ == "__main__":
containers: list[Container] = []
tags: list[str] = []
for container in containers:
for index in range(len(container.samples)):
if container.samples[index].tag is not None:
tags.append(container.samples[index].tag.capitalize())
</code>
<code>from dataclasses import dataclass from typing import Optional @dataclass(frozen=True) class Sample: tag: Optional[str] = None @dataclass(frozen=True) class Container: samples: list[Sample] if __name__ == "__main__": containers: list[Container] = [] tags: list[str] = [] for container in containers: for index in range(len(container.samples)): if container.samples[index].tag is not None: tags.append(container.samples[index].tag.capitalize()) </code>
from dataclasses import dataclass
from typing import Optional


@dataclass(frozen=True)
class Sample:
    tag: Optional[str] = None


@dataclass(frozen=True)
class Container:
    samples: list[Sample]



if __name__ == "__main__":

    containers: list[Container] = []
    tags: list[str] = []

    for container in containers:
        for index in range(len(container.samples)):
            if container.samples[index].tag is not None:
                tags.append(container.samples[index].tag.capitalize())

This gives Item "None" of "str | None" has no attribute "capitalize" Mypyunion-attr error on mypy.

I’ve discovered that the issue vanishes if one avoids indexing and iterates over the elements directly (which I may not)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> for container in containers:
for sample in container.samples:
if sample.tag is not None:
tags.append(sample.tag.capitalize())
</code>
<code> for container in containers: for sample in container.samples: if sample.tag is not None: tags.append(sample.tag.capitalize()) </code>
    for container in containers:
        for sample in container.samples:
            if sample.tag is not None:
                tags.append(sample.tag.capitalize())

so it seems that mypy struggles resolving the type because of the nested structure.

Other workarounds which I cannot use involve asserting or assigning the value to a temporary variable for checking. The walrus operator assignment would do as well:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> for container in containers:
for index in range(len(container.samples)):
if (tag := container.samples[index].tag) is not None:
tags.append(tag.capitalize())
</code>
<code> for container in containers: for index in range(len(container.samples)): if (tag := container.samples[index].tag) is not None: tags.append(tag.capitalize()) </code>
    for container in containers:
        for index in range(len(container.samples)):
            if (tag := container.samples[index].tag) is not None:
                tags.append(tag.capitalize())

but apparently cannot be used in a more complex context (Operator ":=" is not allowed in this context without surrounding parentheses).

What am I missing here?

New contributor

Vexx23 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật