Skip to content

Commit

Permalink
Use PEP570 syntax (#8940)
Browse files Browse the repository at this point in the history
Co-authored-by: Sydney Runkle <54324534+sydney-runkle@users.noreply.github.com>
  • Loading branch information
Viicos and sydney-runkle committed Mar 5, 2024
1 parent af41c8e commit b09e06c
Show file tree
Hide file tree
Showing 18 changed files with 167 additions and 154 deletions.
4 changes: 2 additions & 2 deletions pydantic/_internal/_dataclasses.py
Expand Up @@ -185,8 +185,8 @@ def __init__(__dataclass_self__: PydanticDataclass, *args: Any, **kwargs: Any) -
if config_wrapper.validate_assignment:

@wraps(cls.__setattr__)
def validated_setattr(instance: Any, __field: str, __value: str) -> None:
validator.validate_assignment(instance, __field, __value)
def validated_setattr(instance: Any, field: str, value: str, /) -> None:
validator.validate_assignment(instance, field, value)

cls.__setattr__ = validated_setattr.__get__(None, cls) # type: ignore

Expand Down
8 changes: 4 additions & 4 deletions pydantic/_internal/_decorators.py
Expand Up @@ -635,18 +635,18 @@ def inspect_model_serializer(serializer: Callable[..., Any], mode: Literal['plai
def _serializer_info_arg(mode: Literal['plain', 'wrap'], n_positional: int) -> bool | None:
if mode == 'plain':
if n_positional == 1:
# (__input_value: Any) -> Any
# (input_value: Any, /) -> Any
return False
elif n_positional == 2:
# (__model: Any, __input_value: Any) -> Any
# (model: Any, input_value: Any, /) -> Any
return True
else:
assert mode == 'wrap', f"invalid mode: {mode!r}, expected 'plain' or 'wrap'"
if n_positional == 2:
# (__input_value: Any, __serializer: SerializerFunctionWrapHandler) -> Any
# (input_value: Any, serializer: SerializerFunctionWrapHandler, /) -> Any
return False
elif n_positional == 3:
# (__input_value: Any, __serializer: SerializerFunctionWrapHandler, __info: SerializationInfo) -> Any
# (input_value: Any, serializer: SerializerFunctionWrapHandler, info: SerializationInfo, /) -> Any
return True

return None
Expand Down
8 changes: 4 additions & 4 deletions pydantic/_internal/_generics.py
Expand Up @@ -52,13 +52,13 @@ def __init__(self, size_limit: int = _LIMITED_DICT_SIZE):
self.size_limit = size_limit
super().__init__()

def __setitem__(self, __key: Any, __value: Any) -> None:
super().__setitem__(__key, __value)
def __setitem__(self, key: Any, value: Any, /) -> None:
super().__setitem__(key, value)
if len(self) > self.size_limit:
excess = len(self) - self.size_limit + self.size_limit // 10
to_remove = list(self.keys())[:excess]
for key in to_remove:
del self[key]
for k in to_remove:
del self[k]


# weak dictionaries allow the dynamically created parametrized versions of generic models to get collected
Expand Down
12 changes: 6 additions & 6 deletions pydantic/_internal/_schema_generation_shared.py
Expand Up @@ -32,8 +32,8 @@ def __init__(self, generate_json_schema: GenerateJsonSchema, handler_override: H
self.handler = handler_override or generate_json_schema.generate_inner
self.mode = generate_json_schema.mode

def __call__(self, __core_schema: CoreSchemaOrField) -> JsonSchemaValue:
return self.handler(__core_schema)
def __call__(self, core_schema: CoreSchemaOrField, /) -> JsonSchemaValue:
return self.handler(core_schema)

def resolve_ref_schema(self, maybe_ref_json_schema: JsonSchemaValue) -> JsonSchemaValue:
"""Resolves `$ref` in the json schema.
Expand Down Expand Up @@ -78,8 +78,8 @@ def __init__(
self._generate_schema = generate_schema
self._ref_mode = ref_mode

def __call__(self, __source_type: Any) -> core_schema.CoreSchema:
schema = self._handler(__source_type)
def __call__(self, source_type: Any, /) -> core_schema.CoreSchema:
schema = self._handler(source_type)
ref = schema.get('ref')
if self._ref_mode == 'to-def':
if ref is not None:
Expand All @@ -92,8 +92,8 @@ def __call__(self, __source_type: Any) -> core_schema.CoreSchema:
def _get_types_namespace(self) -> dict[str, Any] | None:
return self._generate_schema._types_namespace

def generate_schema(self, __source_type: Any) -> core_schema.CoreSchema:
return self._generate_schema.generate_schema(__source_type)
def generate_schema(self, source_type: Any, /) -> core_schema.CoreSchema:
return self._generate_schema.generate_schema(source_type)

@property
def field_name(self) -> str | None:
Expand Down
4 changes: 2 additions & 2 deletions pydantic/_internal/_std_types_schema.py
Expand Up @@ -86,9 +86,9 @@ def get_json_schema(_, handler: GetJsonSchemaHandler) -> JsonSchemaValue:
else:
expected = ', '.join([repr(case.value) for case in cases[:-1]]) + f' or {cases[-1].value!r}'

def to_enum(__input_value: Any) -> Enum:
def to_enum(input_value: Any, /) -> Enum:
try:
return enum_type(__input_value)
return enum_type(input_value)
except ValueError:
# The type: ignore on the next line is to ignore the requirement of LiteralString
raise PydanticCustomError('enum', f'Input should be {expected}', {'expected': expected}) # type: ignore
Expand Down
8 changes: 4 additions & 4 deletions pydantic/_internal/_utils.py
Expand Up @@ -349,14 +349,14 @@ class SafeGetItemProxy:

wrapped: Mapping[str, Any]

def __getitem__(self, __key: str) -> Any:
return self.wrapped.get(__key, _SENTINEL)
def __getitem__(self, key: str, /) -> Any:
return self.wrapped.get(key, _SENTINEL)

# required to pass the object to operator.itemgetter() instances due to a quirk of typeshed
# https://github.com/python/mypy/issues/13713
# https://github.com/python/typeshed/pull/8785
# Since this is typing-only, hide it in a typing.TYPE_CHECKING block
if typing.TYPE_CHECKING:

def __contains__(self, __key: str) -> bool:
return self.wrapped.__contains__(__key)
def __contains__(self, key: str, /) -> bool:
return self.wrapped.__contains__(key)
95 changes: 48 additions & 47 deletions pydantic/_internal/_validators.py
Expand Up @@ -16,11 +16,12 @@


def sequence_validator(
__input_value: typing.Sequence[Any],
input_value: typing.Sequence[Any],
/,
validator: core_schema.ValidatorFunctionWrapHandler,
) -> typing.Sequence[Any]:
"""Validator for `Sequence` types, isinstance(v, Sequence) has already been called."""
value_type = type(__input_value)
value_type = type(input_value)

# We don't accept any plain string as a sequence
# Relevant issue: https://github.com/pydantic/pydantic/issues/5595
Expand All @@ -37,9 +38,9 @@ def sequence_validator(
# SequenceValidator in _std_types_schema.py (preferably this one, while porting over some logic).
# Effectively, a refactor for sequence validation is needed.
if value_type == tuple:
__input_value = list(__input_value)
input_value = list(input_value)

v_list = validator(__input_value)
v_list = validator(input_value)

# the rest of the logic is just re-creating the original type from `v_list`
if value_type == list:
Expand Down Expand Up @@ -116,39 +117,39 @@ def _import_string_logic(dotted_path: str) -> Any:
return module


def pattern_either_validator(__input_value: Any) -> typing.Pattern[Any]:
if isinstance(__input_value, typing.Pattern):
return __input_value
elif isinstance(__input_value, (str, bytes)):
def pattern_either_validator(input_value: Any, /) -> typing.Pattern[Any]:
if isinstance(input_value, typing.Pattern):
return input_value
elif isinstance(input_value, (str, bytes)):
# todo strict mode
return compile_pattern(__input_value) # type: ignore
return compile_pattern(input_value) # type: ignore
else:
raise PydanticCustomError('pattern_type', 'Input should be a valid pattern')


def pattern_str_validator(__input_value: Any) -> typing.Pattern[str]:
if isinstance(__input_value, typing.Pattern):
if isinstance(__input_value.pattern, str):
return __input_value
def pattern_str_validator(input_value: Any, /) -> typing.Pattern[str]:
if isinstance(input_value, typing.Pattern):
if isinstance(input_value.pattern, str):
return input_value
else:
raise PydanticCustomError('pattern_str_type', 'Input should be a string pattern')
elif isinstance(__input_value, str):
return compile_pattern(__input_value)
elif isinstance(__input_value, bytes):
elif isinstance(input_value, str):
return compile_pattern(input_value)
elif isinstance(input_value, bytes):
raise PydanticCustomError('pattern_str_type', 'Input should be a string pattern')
else:
raise PydanticCustomError('pattern_type', 'Input should be a valid pattern')


def pattern_bytes_validator(__input_value: Any) -> typing.Pattern[bytes]:
if isinstance(__input_value, typing.Pattern):
if isinstance(__input_value.pattern, bytes):
return __input_value
def pattern_bytes_validator(input_value: Any, /) -> typing.Pattern[bytes]:
if isinstance(input_value, typing.Pattern):
if isinstance(input_value.pattern, bytes):
return input_value
else:
raise PydanticCustomError('pattern_bytes_type', 'Input should be a bytes pattern')
elif isinstance(__input_value, bytes):
return compile_pattern(__input_value)
elif isinstance(__input_value, str):
elif isinstance(input_value, bytes):
return compile_pattern(input_value)
elif isinstance(input_value, str):
raise PydanticCustomError('pattern_bytes_type', 'Input should be a bytes pattern')
else:
raise PydanticCustomError('pattern_type', 'Input should be a valid pattern')
Expand All @@ -164,72 +165,72 @@ def compile_pattern(pattern: PatternType) -> typing.Pattern[PatternType]:
raise PydanticCustomError('pattern_regex', 'Input should be a valid regular expression')


def ip_v4_address_validator(__input_value: Any) -> IPv4Address:
if isinstance(__input_value, IPv4Address):
return __input_value
def ip_v4_address_validator(input_value: Any, /) -> IPv4Address:
if isinstance(input_value, IPv4Address):
return input_value

try:
return IPv4Address(__input_value)
return IPv4Address(input_value)
except ValueError:
raise PydanticCustomError('ip_v4_address', 'Input is not a valid IPv4 address')


def ip_v6_address_validator(__input_value: Any) -> IPv6Address:
if isinstance(__input_value, IPv6Address):
return __input_value
def ip_v6_address_validator(input_value: Any, /) -> IPv6Address:
if isinstance(input_value, IPv6Address):
return input_value

try:
return IPv6Address(__input_value)
return IPv6Address(input_value)
except ValueError:
raise PydanticCustomError('ip_v6_address', 'Input is not a valid IPv6 address')


def ip_v4_network_validator(__input_value: Any) -> IPv4Network:
def ip_v4_network_validator(input_value: Any, /) -> IPv4Network:
"""Assume IPv4Network initialised with a default `strict` argument.
See more:
https://docs.python.org/library/ipaddress.html#ipaddress.IPv4Network
"""
if isinstance(__input_value, IPv4Network):
return __input_value
if isinstance(input_value, IPv4Network):
return input_value

try:
return IPv4Network(__input_value)
return IPv4Network(input_value)
except ValueError:
raise PydanticCustomError('ip_v4_network', 'Input is not a valid IPv4 network')


def ip_v6_network_validator(__input_value: Any) -> IPv6Network:
def ip_v6_network_validator(input_value: Any, /) -> IPv6Network:
"""Assume IPv6Network initialised with a default `strict` argument.
See more:
https://docs.python.org/library/ipaddress.html#ipaddress.IPv6Network
"""
if isinstance(__input_value, IPv6Network):
return __input_value
if isinstance(input_value, IPv6Network):
return input_value

try:
return IPv6Network(__input_value)
return IPv6Network(input_value)
except ValueError:
raise PydanticCustomError('ip_v6_network', 'Input is not a valid IPv6 network')


def ip_v4_interface_validator(__input_value: Any) -> IPv4Interface:
if isinstance(__input_value, IPv4Interface):
return __input_value
def ip_v4_interface_validator(input_value: Any, /) -> IPv4Interface:
if isinstance(input_value, IPv4Interface):
return input_value

try:
return IPv4Interface(__input_value)
return IPv4Interface(input_value)
except ValueError:
raise PydanticCustomError('ip_v4_interface', 'Input is not a valid IPv4 interface')


def ip_v6_interface_validator(__input_value: Any) -> IPv6Interface:
if isinstance(__input_value, IPv6Interface):
return __input_value
def ip_v6_interface_validator(input_value: Any, /) -> IPv6Interface:
if isinstance(input_value, IPv6Interface):
return input_value

try:
return IPv6Interface(__input_value)
return IPv6Interface(input_value)
except ValueError:
raise PydanticCustomError('ip_v6_interface', 'Input is not a valid IPv6 interface')

Expand Down
20 changes: 10 additions & 10 deletions pydantic/annotated_handlers.py
Expand Up @@ -28,29 +28,29 @@ class GetJsonSchemaHandler:

mode: JsonSchemaMode

def __call__(self, __core_schema: CoreSchemaOrField) -> JsonSchemaValue:
def __call__(self, core_schema: CoreSchemaOrField, /) -> JsonSchemaValue:
"""Call the inner handler and get the JsonSchemaValue it returns.
This will call the next JSON schema modifying function up until it calls
into `pydantic.json_schema.GenerateJsonSchema`, which will raise a
`pydantic.errors.PydanticInvalidForJsonSchema` error if it cannot generate
a JSON schema.
Args:
__core_schema: A `pydantic_core.core_schema.CoreSchema`.
core_schema: A `pydantic_core.core_schema.CoreSchema`.
Returns:
JsonSchemaValue: The JSON schema generated by the inner JSON schema modify
functions.
"""
raise NotImplementedError

def resolve_ref_schema(self, __maybe_ref_json_schema: JsonSchemaValue) -> JsonSchemaValue:
def resolve_ref_schema(self, maybe_ref_json_schema: JsonSchemaValue, /) -> JsonSchemaValue:
"""Get the real schema for a `{"$ref": ...}` schema.
If the schema given is not a `$ref` schema, it will be returned as is.
This means you don't have to check before calling this function.
Args:
__maybe_ref_json_schema: A JsonSchemaValue which may be a `$ref` schema.
maybe_ref_json_schema: A JsonSchemaValue which may be a `$ref` schema.
Raises:
LookupError: If the ref is not found.
Expand All @@ -64,43 +64,43 @@ def resolve_ref_schema(self, __maybe_ref_json_schema: JsonSchemaValue) -> JsonSc
class GetCoreSchemaHandler:
"""Handler to call into the next CoreSchema schema generation function."""

def __call__(self, __source_type: Any) -> core_schema.CoreSchema:
def __call__(self, source_type: Any, /) -> core_schema.CoreSchema:
"""Call the inner handler and get the CoreSchema it returns.
This will call the next CoreSchema modifying function up until it calls
into Pydantic's internal schema generation machinery, which will raise a
`pydantic.errors.PydanticSchemaGenerationError` error if it cannot generate
a CoreSchema for the given source type.
Args:
__source_type: The input type.
source_type: The input type.
Returns:
CoreSchema: The `pydantic-core` CoreSchema generated.
"""
raise NotImplementedError

def generate_schema(self, __source_type: Any) -> core_schema.CoreSchema:
def generate_schema(self, source_type: Any, /) -> core_schema.CoreSchema:
"""Generate a schema unrelated to the current context.
Use this function if e.g. you are handling schema generation for a sequence
and want to generate a schema for its items.
Otherwise, you may end up doing something like applying a `min_length` constraint
that was intended for the sequence itself to its items!
Args:
__source_type: The input type.
source_type: The input type.
Returns:
CoreSchema: The `pydantic-core` CoreSchema generated.
"""
raise NotImplementedError

def resolve_ref_schema(self, __maybe_ref_schema: core_schema.CoreSchema) -> core_schema.CoreSchema:
def resolve_ref_schema(self, maybe_ref_schema: core_schema.CoreSchema, /) -> core_schema.CoreSchema:
"""Get the real schema for a `definition-ref` schema.
If the schema given is not a `definition-ref` schema, it will be returned as is.
This means you don't have to check before calling this function.
Args:
__maybe_ref_schema: A `CoreSchema`, `ref`-based or not.
maybe_ref_schema: A `CoreSchema`, `ref`-based or not.
Raises:
LookupError: If the `ref` is not found.
Expand Down

0 comments on commit b09e06c

Please sign in to comment.