Skip to content

Commit

Permalink
Allow subclasses of SecretStr to expect str
Browse files Browse the repository at this point in the history
Currently subclasses of SecretStr fail to evaluate
`self.field_type is SecretStr` and default to `bytes_type`. This is not
how it should go as the subclass explicitly subclasses the SecretStr
type.

This fix tests if the type is of SecretStr with `issubclass` which
states:

>  A class is considered a subclass of itself

Which makes is backwards compatible for the actual SecretStr as well.
  • Loading branch information
AlexVndnblcke committed Jul 18, 2023
1 parent f4f35a9 commit c6a25ad
Showing 1 changed file with 3 additions and 3 deletions.
6 changes: 3 additions & 3 deletions pydantic/types.py
Expand Up @@ -728,7 +728,7 @@ class _SecretFieldValidator:
inner_schema: CoreSchema = _dataclasses.field(init=False)

def validate(self, value: _SecretField[SecretType] | SecretType, _: core_schema.ValidationInfo) -> Any:
error_prefix: Literal['string', 'bytes'] = 'string' if self.field_type is SecretStr else 'bytes'
error_prefix: Literal['string', 'bytes'] = 'string' if issubclass(self.field_type, SecretStr) else 'bytes'
if self.min_length is not None and len(value) < self.min_length:
short_kind: core_schema.ErrorType = f'{error_prefix}_too_short' # type: ignore[assignment]
raise PydanticKnownError(short_kind, {'min_length': self.min_length})
Expand Down Expand Up @@ -771,8 +771,8 @@ def __get_pydantic_json_schema__(
def __get_pydantic_core_schema__(
self, source: type[Any], handler: _annotated_handlers.GetCoreSchemaHandler
) -> core_schema.CoreSchema:
self.inner_schema = handler(str if self.field_type is SecretStr else bytes)
error_kind = 'string_type' if self.field_type is SecretStr else 'bytes_type'
self.inner_schema = handler(str if issubclass(self.field_type, SecretStr) else bytes)
error_kind = 'string_type' if issubclass(self.field_type, SecretStr) else 'bytes_type'
return core_schema.general_after_validator_function(
self.validate,
core_schema.union_schema(
Expand Down

0 comments on commit c6a25ad

Please sign in to comment.