[Python] How do you check a value against a type?

Discussão em 'Python' iniciado por Stack, Julho 2, 2025.

  1. Stack

    Stack Membro Participativo

    from annotated_types import Annotated, Ge
    type PosInt = Annotated[int, Ge(0)]
    assert -3 … … … PosInt


    The documentation talks about setting up class attributes, but I have a plain value. I tried isinstance, but that does not work.

    Compare these examples from other languages:

    use Types::Standard qw(Int);
    use Type::Utils qw(declare as where);
    my $PosInt = declare "PosInt", as Int, where {$_ >= 0};
    $PosInt->assert_return(-3);
    ___END__
    Value "-3" did not pass type constraint "PosInt"


    import * as v from 'valibot';
    const PosInt = v.pipe(
    v.number(),
    v.integer(),
    v.check((_: number) => _ >= 0)
    );
    v.parse(PosInt, -3);
    // ValiError: Invalid input: Received -3

    Continue reading...

Compartilhe esta Página