[Python] How to create a literal TypeGuard in Python?

Discussão em 'Python' iniciado por Stack, Fevereiro 25, 2025.

  1. Stack

    Stack Membro Participativo

    I'd like to have a TypeGuard of property names in Python. The source values come from 3rd party source, so I need to validate them effectively.

    To simplify, let's say I' making an app listing people's dogs. Each dog has just 3 properties:

    1. name
    2. birth_date
    3. favorite_food

    Now, here's how my TypeGuard looks so far:

    from typing import Literal, TypeGuard


    type DogPropertyName = Literal["name", "birth_date", "favorite_food"]


    def is_dog_property_name(value: str) -> TypeGuard[DogPropertyName]:
    return value in ["name", "birth_date", "favorite_food"]


    The problem is that I needed to repeat the correct values. I also tried to unpack a tuple, but it's not allowed:

    dog_property_names = ("name", "birth_date", "favorite_food")


    type DogPropertyName = Literal[*dog_property_names]
    # Error: Unpacked arguments cannot be used in this context


    def is_dog_property_name(value: str) -> TypeGuard[DogPropertyName]:
    return value in dog_property_names


    Can I use Literal TypeGuard like this?

    Continue reading...

Compartilhe esta Página