Skip to content

Commit

Permalink
Expose regex_engine flag (#7768)
Browse files Browse the repository at this point in the history
  • Loading branch information
utkini committed Oct 24, 2023
1 parent df1bb06 commit aaf552d
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
3 changes: 3 additions & 0 deletions pydantic/_internal/_config.py
Expand Up @@ -80,6 +80,7 @@ class ConfigWrapper:
json_schema_serialization_defaults_required: bool
json_schema_mode_override: Literal['validation', 'serialization', None]
coerce_numbers_to_str: bool
regex_engine: Literal['rust-regex', 'python-re']

def __init__(self, config: ConfigDict | dict[str, Any] | type[Any] | None, *, check: bool = True):
if check:
Expand Down Expand Up @@ -176,6 +177,7 @@ def dict_not_none(**kwargs: Any) -> Any:
str_min_length=self.config_dict.get('str_min_length'),
hide_input_in_errors=self.config_dict.get('hide_input_in_errors'),
coerce_numbers_to_str=self.config_dict.get('coerce_numbers_to_str'),
regex_engine=self.config_dict.get('regex_engine'),
)
)
return core_config
Expand Down Expand Up @@ -248,6 +250,7 @@ def _context_manager() -> Iterator[None]:
json_schema_serialization_defaults_required=False,
json_schema_mode_override=None,
coerce_numbers_to_str=False,
regex_engine='rust-regex',
)


Expand Down
33 changes: 33 additions & 0 deletions pydantic/config.py
Expand Up @@ -824,5 +824,38 @@ class Model(BaseModel):
```
"""

regex_engine: Literal['rust-regex', 'python-re']
"""
The regex engine to used for pattern validation
Defaults to `'rust-regex'`.
- `rust-regex` uses the [`regex`](https://docs.rs/regex) Rust crate,
which is non-backtracking and therefore more DDoS resistant, but does not support all regex features.
- `python-re` use the [`re`](https://docs.python.org/3/library/re.html) module,
which supports all regex features, but may be slower.
```py
from pydantic import BaseModel, ConfigDict, Field, ValidationError
class Model(BaseModel):
model_config = ConfigDict(regex_engine='python-re')
value: str = Field(pattern=r'^abc(?=def)')
print(Model(value='abcdef').value)
#> abcdef
try:
print(Model(value='abxyzcdef'))
except ValidationError as e:
print(e)
'''
1 validation error for Model
value
String should match pattern '^abc(?=def)' [type=string_pattern_mismatch, input_value='abxyzcdef', input_type=str]
'''
```
"""


__getattr__ = getattr_migration(__name__)

0 comments on commit aaf552d

Please sign in to comment.