Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expose regex_engine flag #7768

Merged
merged 1 commit into from Oct 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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 @@ -787,5 +787,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__)