Skip to content

Union-attr method chaining #1118

Answered by JelleZijlstra
gfcq88 asked this question in Q&A
Discussion options

You must be logged in to vote

In our codebase we have this helper function:

from typing import TypeVar, Optional

T = TypeVar("T")


def not_none(obj: Optional[T], *, message: Optional[str] = None) -> T:
    """Check that obj is not None. Raises TypeError if it is.

    This is meant to help get code to type check that uses Optional types.

    """
    if obj is None:
        if message is not None:
            raise TypeError(message)
        raise TypeError("object is unexpectedly None")
    return obj

In your code, you'd write text = not_none(not_none(element).parent).next_sibling.text. This satisfies the type checker and also allows you to give a nice error message if the object happens to be None at runtime.

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@gfcq88
Comment options

Answer selected by gfcq88
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants