WARNING: THIS SITE IS A MIRROR OF GITHUB.COM / IT CANNOT LOGIN OR REGISTER ACCOUNTS / THE CONTENTS ARE PROVIDED AS-IS / THIS SITE ASSUMES NO RESPONSIBILITY FOR ANY DISPLAYED CONTENT OR LINKS / IF YOU FOUND SOMETHING MAY NOT GOOD FOR EVERYONE, CONTACT ADMIN AT ilovescratch@foxmail.com
Skip to content

How to handle Optional values with lxml and mypy? #103

@jtherrmann

Description

@jtherrmann

A common error when running mypy on a project that uses lxml is that many of the lxml methods for retrieving information from XML trees return Optional values (i.e. a value that can be None or some other type such as _Element or str). This causes mypy to report many union-attr errors such as Item "None" of "Optional[_Element]" has no attribute "text".

The only "correct" solution that I'm aware of is to use type narrowing techniques such as assert value is not None or cast(_Element, value). This leads to a lot of verbose code for no real benefit, because in most cases I've tested the code enough to be confident that optional values will not be None at runtime, or I'm fine with a runtime AttributeError.

For those who use mypy with lxml, what's your solution for these errors? Is there a correct, non-verbose way to handle/silence them, or some way to tell mypy to ignore all union-attr errors that originate from lxml?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions