|
23 | 23 | # SOFTWARE. |
24 | 24 | # |
25 | 25 | ############################################################################### |
26 | | -from pydantic import BaseModel |
| 26 | +from typing import Any |
| 27 | + |
| 28 | +from pydantic import BaseModel, model_validator |
27 | 29 |
|
28 | 30 |
|
29 | 31 | class AnalyzerArgs(BaseModel): |
| 32 | + """Base class for all analyzer arguments. |
| 33 | +
|
| 34 | + This class provides automatic string stripping for all string values |
| 35 | + in analyzer args. All analyzer args classes should inherit from this |
| 36 | + directly. |
| 37 | +
|
| 38 | + """ |
| 39 | + |
30 | 40 | model_config = {"extra": "forbid", "exclude_none": True} |
31 | 41 |
|
| 42 | + @model_validator(mode="before") |
| 43 | + @classmethod |
| 44 | + def strip_string_values(cls, data: Any) -> Any: |
| 45 | + """Strip whitespace from all string values in analyzer args. |
| 46 | +
|
| 47 | + This validator recursively processes: |
| 48 | + - String values: strips whitespace |
| 49 | + - Lists: strips strings in lists |
| 50 | + - Dicts: strips string values in dicts |
| 51 | + - Other types: left unchanged |
| 52 | +
|
| 53 | + Args: |
| 54 | + data: The input data to validate |
| 55 | +
|
| 56 | + Returns: |
| 57 | + The data with all string values stripped |
| 58 | + """ |
| 59 | + if isinstance(data, dict): |
| 60 | + return {k: cls._strip_value(v) for k, v in data.items()} |
| 61 | + return data |
| 62 | + |
| 63 | + @classmethod |
| 64 | + def _strip_value(cls, value: Any) -> Any: |
| 65 | + """Recursively strip string values. |
| 66 | +
|
| 67 | + Args: |
| 68 | + value: The value to process |
| 69 | +
|
| 70 | + Returns: |
| 71 | + The processed value |
| 72 | + """ |
| 73 | + if isinstance(value, str): |
| 74 | + return value.strip() |
| 75 | + elif isinstance(value, list): |
| 76 | + return [cls._strip_value(item) for item in value] |
| 77 | + elif isinstance(value, dict): |
| 78 | + return {k: cls._strip_value(v) for k, v in value.items()} |
| 79 | + return value |
| 80 | + |
32 | 81 | @classmethod |
33 | 82 | def build_from_model(cls, datamodel): |
34 | 83 | """Build analyzer args instance from data model object |
|
0 commit comments