[Python] Propagate assertion type check to caller

Discussão em 'Python' iniciado por Stack, Abril 1, 2025.

  1. Stack

    Stack Membro Participativo

    I want to assert the type of an object in a function without having to return it, but I can't find how to do it.

    For example:

    from typing import Optional, TypeVar

    T = TypeVar('T')

    def assert_non_null(_object: Optional[T]):
    assert _object is not None

    def f(a: Optional[float]):
    assert_non_null(a)
    b: float = a # error because "a" can be null


    Whereas this works (but its not what I'm looking for):

    from typing import Optional, TypeVar

    T = TypeVar('T')

    def extract_non_null(_object: Optional[T]):
    assert _object is not None
    return _object

    def g(a: Optional[float]):
    a = extract_non_null(a)
    b: float = a # its fine because the function returns the type T (float)


    Is there a way to add type annotation on side effects to make sure calling assert_non_null has the same effect as calling assert is not None directly?

    Continue reading...

Compartilhe esta Página