[Python] Static typing for an `Enum` that contains compiled regex patterns

Discussão em 'Python' iniciado por Stack, Setembro 16, 2025.

  1. Stack

    Stack Membro Participativo

    I am in a scenario (that could be compared to writing an AST) where I compile multiple regex patterns that I want to reuse later, and for the sake of simplicity and readability I want to store them in an Enum. It works properly:

    import re
    import enum

    class Patterns(enum.Enum):
    """
    Patterns used to read type declarations in `xyz` files.
    """
    Simple: re.Pattern = re.compile(r"([\w_]+)\s*[\|;]")
    Complex: re.Pattern = re.compile(r"([\w_]+)\s*:\s*([\w_]+)")


    When I want to use them, I'll for instance write:

    text = "{ a : alpha; b : bravo; c : charlie}"
    pattern = Patterns.Complex
    print(dict(pattern.findall(text))) # doesn't work


    However, pattern being of type <Enum: Patterns>, pattern does not have a findall method. For int or str (or many other types), this is fixed by subclassing both Enum and str for instance:

    class color(str, enum.Enum):
    R = "red"
    G = "green"
    B = "blue"

    print(color.B.upper())
    # BLUE


    In Python, regex patterns obtained via re.compile(pattern) are of type re.Pattern, that is marked as typing.Final and therefore should not be subclassed (you still can of course, but static type checkers will heavily complain about it). A workaround is to extract the value of the Enum member, but that's not the most convenient to use:

    print(dict(pattern.value.findall(text))) # works


    I'm trying to find a better, cleaner way to do this.

    Continue reading...

Compartilhe esta Página