[Python] How to use Python type hinting to mock values and perform static analysis when a...

Discussão em 'Python' iniciado por Stack, Março 28, 2025.

  1. Stack

    Stack Membro Participativo

    I’m working with some external Python code that I cannot modify. This code interacts with my own code, and while I can't add type annotations or assert statements to the external code, I can mock certain pieces for static analysis.

    The goal is to mock a class that has a value bound at runtime (i.e., ival) and perform static analysis to ensure that values remain within a defined range during static analysis (e.g., 1 ≤ ival ≤ 100).

    At runtime, however, the value of ival can exceed this bound. For example, I want to flag certain conditions where the value of ival is used in comparisons that should be unreachable (such as comparing against a number larger than the max value).

    Here's a simplified version of the code:

    # Pseudo type code
    BoundedInt1To100 = Int[1-100]

    class MockMyClass:
    def __init__(self, min_val: int, max_val: int, value: int):
    self.min = min_val
    self.max = max_val
    self._value = value

    @property
    def ival(self) -> BoundedInt0To100:
    return self._value

    mock100 = MockMyClass(1, 100, 50)

    # This comparison should be flagged as unreachable during static analysis
    if mock100.ival > 220:
    print("This should be flagged as unreachable since 220 exceeds max value of 100.")


    I’ve explored the typing module, but I didn’t find a direct way to enforce value ranges at static analysis time while allowing runtime flexibility.

    I’ve tried using custom classes for type hints, but I can’t find an elegant solution to mock the runtime behavior while ensuring correct static analysis.

    Continue reading...

Compartilhe esta Página