Skip to content

Commit

Permalink
📝 Add docstrings for top level modules (#6053)
Browse files Browse the repository at this point in the history
  • Loading branch information
Kludex committed Jun 8, 2023
1 parent 0e337dc commit 31a4ac3
Show file tree
Hide file tree
Showing 9 changed files with 317 additions and 101 deletions.
13 changes: 12 additions & 1 deletion pydantic/__init__.py
Expand Up @@ -25,7 +25,14 @@
from .errors import *
from .fields import AliasChoices, AliasPath, Field, PrivateAttr, computed_field
from .functional_serializers import PlainSerializer, WrapSerializer, field_serializer, model_serializer
from .functional_validators import field_validator, model_validator
from .functional_validators import (
AfterValidator,
BeforeValidator,
PlainValidator,
WrapValidator,
field_validator,
model_validator,
)
from .main import *
from .networks import *
from .type_adapter import TypeAdapter
Expand All @@ -49,6 +56,10 @@
'ValidatorFunctionWrapHandler',
'field_validator',
'model_validator',
'AfterValidator',
'BeforeValidator',
'PlainValidator',
'WrapValidator',
# deprecated V1 functional validators
'root_validator',
'validator',
Expand Down
2 changes: 1 addition & 1 deletion pydantic/deprecated/config.py
Expand Up @@ -25,7 +25,7 @@ class BaseConfig(metaclass=_ConfigMetaclass):
"""
This class is only retained for backwards compatibility.
The preferred approach going forward is to assign a ConfigDict to the `model_config` attribute of the Model class.
The preferred approach going forward is to assign a `ConfigDict` to the `model_config` attribute of the Model class.
"""

def __getattr__(self, item: str) -> Any:
Expand Down
14 changes: 7 additions & 7 deletions pydantic/errors.py
Expand Up @@ -64,8 +64,8 @@ class PydanticErrorMixin:
A mixin class for common functionality shared by all Pydantic-specific errors.
Attributes:
message (str): A message describing the error.
code (PydanticErrorCodes | None): An optional error code from PydanticErrorCodes enum.
message: A message describing the error.
code: An optional error code from PydanticErrorCodes enum.
"""

def __init__(self, message: str, *, code: PydanticErrorCodes | None) -> None:
Expand All @@ -89,8 +89,8 @@ class PydanticUndefinedAnnotation(PydanticErrorMixin, NameError):
"""A subclass of `NameError` raised when handling undefined annotations during `CoreSchema` generation.
Attributes:
name (str): Name of the error.
message (str): Description of the error.
name: Name of the error.
message: Description of the error.
"""

def __init__(self, name: str, message: str) -> None:
Expand Down Expand Up @@ -120,7 +120,7 @@ class PydanticImportError(PydanticErrorMixin, ImportError):
Error raised when an import fails due to module changes between V1 and V2.
Attributes:
message (str): Description of the error.
message: Description of the error.
"""

def __init__(self, message: str) -> None:
Expand All @@ -132,7 +132,7 @@ class PydanticSchemaGenerationError(PydanticUserError):
Error raised during failures to generate a `CoreSchema` for some type.
Attributes:
message (str): Description of the error.
message: Description of the error.
"""

def __init__(self, message: str) -> None:
Expand All @@ -144,7 +144,7 @@ class PydanticInvalidForJsonSchema(PydanticUserError):
Error raised during failures to generate a JSON schema for some `CoreSchema`.
Attributes:
message (str): Description of the error.
message: Description of the error.
"""

def __init__(self, message: str) -> None:
Expand Down
33 changes: 6 additions & 27 deletions pydantic/fields.py
Expand Up @@ -603,10 +603,8 @@ class _EmptyKwargs(typing_extensions.TypedDict):
This class exists solely to ensure that type checking warns about passing `**extra` in `Field`.
"""

pass


def Field( # noqa C901
def Field( # C901
default: Any = _Undefined,
*,
default_factory: typing.Callable[[], Any] | None = None,
Expand Down Expand Up @@ -730,9 +728,8 @@ def Field( # noqa C901
if not json_schema_extra:
json_schema_extra = extra # type: ignore

if validation_alias:
if not isinstance(validation_alias, (str, AliasChoices, AliasPath)):
raise TypeError('Invalid `validation_alias` type. it should be `str`, `AliasChoices`, or `AliasPath`')
if validation_alias and not isinstance(validation_alias, (str, AliasChoices, AliasPath)):
raise TypeError('Invalid `validation_alias` type. it should be `str`, `AliasChoices`, or `AliasPath`')

if serialization_alias is None and isinstance(alias, str):
serialization_alias = alias
Expand Down Expand Up @@ -776,8 +773,8 @@ class ModelPrivateAttr(_repr.Representation):
"""A descriptor for private attributes in class models.
Attributes:
default (Any): The default value of the attribute if not provided.
default_factory (typing.Callable[[], Any]): A callable function that generates the default value of the
default: The default value of the attribute if not provided.
default_factory: A callable function that generates the default value of the
attribute if not provided.
"""

Expand Down Expand Up @@ -810,7 +807,7 @@ def __set_name__(self, cls: type[Any], name: str) -> None:
set_name(cls, name)

def get_default(self) -> Any:
"""Returns the default value for the object.
"""Retrieve the default value of the object.
If `self.default_factory` is `None`, the method will return a deep copy of the `self.default` object.
Expand Down Expand Up @@ -890,24 +887,6 @@ class ComputedFieldInfo:
# this should really be `property[T], cached_proprety[T]` but property is not generic unlike cached_property
# See https://github.com/python/typing/issues/985 and linked issues
PropertyT = typing.TypeVar('PropertyT')
"""
`TypeVar` that can be used to specify the type of a property.
This can be used in combination with the `@property` decorator to specify the type
of the property.
Example:
```py
class MyClass:
@property
def my_property(self) -> PropertyT:
return self._my_property
@my_property.setter
def my_property(self, value: PropertyT) -> None:
self._my_property = value
```
"""


@typing.overload
Expand Down
13 changes: 7 additions & 6 deletions pydantic/functional_serializers.py
Expand Up @@ -16,10 +16,10 @@ class PlainSerializer:
Plain serializers use a function to modify the output of serialization.
Attributes:
func (core_schema.SerializerFunction): The serializer function.
func: The serializer function.
return_type: Optional return type for the function, if omitted it will be inferred from the type annotation.
when_used (Literal['always', 'unless-none', 'json', 'json-unless-none'], optional): The serialization condition.
Defaults to 'always'.
when_used: The serialization condition. Accepts a string with values `'always'`, `'unless-none'`, `'json'`,
and `'json-unless-none'`. Defaults to 'always'.
"""

func: core_schema.SerializerFunction
Expand Down Expand Up @@ -58,9 +58,10 @@ class WrapSerializer:
and can modify the resulting value before returning it as the final output of serialization.
Attributes:
func (core_schema.WrapSerializerFunction): The function to be wrapped.
func: The function to be wrapped.
return_type: Optional return type for the function, if omitted it will be inferred from the type annotation.
when_used: Determines the serializer will be used for serialization.
when_used: Determines the serializer will be used for serialization. Accepts a string with values `'always'`,
`'unless-none'`, `'json'`, and `'json-unless-none'`. Defaults to 'always'.
"""

func: core_schema.WrapSerializerFunction
Expand Down Expand Up @@ -159,7 +160,7 @@ def field_serializer(
default serialization logic.
return_type: Optional return type for the function, if omitted it will be inferred from the type annotation.
when_used: Determines the serializer will be used for serialization.
check_fields (bool): Whether to check that the fields actually exist on the model.
check_fields: Whether to check that the fields actually exist on the model.
Returns:
A decorator that can be used to decorate a function to be used as a field serializer.
Expand Down
115 changes: 115 additions & 0 deletions pydantic/functional_validators.py
Expand Up @@ -23,6 +23,43 @@

@_internal_dataclass.slots_dataclass(frozen=True)
class AfterValidator:
'''
A metadata class that indicates that a validation should be applied **after** the inner validation logic.
Example:
```py
from typing import Annotated
from pydantic import BaseModel, AfterValidator, ValidationError
MyInt = Annotated[int, AfterValidator(lambda v: v + 1)]
class Model(BaseModel):
a: MyInt
print(Model(a=1).a)
# > 2
try:
Model(a='a')
except ValidationError as e:
print(e.json(indent=2))
"""
[
{
"type": "int_parsing",
"loc": [
"a"
],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "a",
"url": "https://errors.pydantic.dev/0.38.0/v/int_parsing"
}
]
"""
'''

func: core_schema.NoInfoValidatorFunction | core_schema.GeneralValidatorFunction

def __get_pydantic_core_schema__(self, source_type: Any, handler: _GetCoreSchemaHandler) -> core_schema.CoreSchema:
Expand All @@ -36,6 +73,31 @@ def __get_pydantic_core_schema__(self, source_type: Any, handler: _GetCoreSchema

@_internal_dataclass.slots_dataclass(frozen=True)
class BeforeValidator:
"""A metadata class that indicates that a validation should be applied **before** the inner validation logic.
Example:
```py
from typing import Annotated
from pydantic import BaseModel, BeforeValidator
MyInt = Annotated[int, BeforeValidator(lambda v: v + 1)]
class Model(BaseModel):
a: MyInt
print(Model(a=1).a)
# > 2
try:
Model(a='a')
except TypeError as e:
print(e)
#> can only concatenate str (not "int") to str
```
"""

func: core_schema.NoInfoValidatorFunction | core_schema.GeneralValidatorFunction

def __get_pydantic_core_schema__(self, source_type: Any, handler: _GetCoreSchemaHandler) -> core_schema.CoreSchema:
Expand All @@ -49,6 +111,25 @@ def __get_pydantic_core_schema__(self, source_type: Any, handler: _GetCoreSchema

@_internal_dataclass.slots_dataclass(frozen=True)
class PlainValidator:
"""A metadata class that indicates that a validation should be applied **instead** of the inner validation logic.
Example:
```py
from typing import Annotated
from pydantic import BaseModel, PlainValidator
MyInt = Annotated[int, PlainValidator(lambda v: int(v) + 1)]
class Model(BaseModel):
a: MyInt
print(Model(a='1').a)
# > 2
```
"""

func: core_schema.NoInfoValidatorFunction | core_schema.GeneralValidatorFunction

def __get_pydantic_core_schema__(self, source_type: Any, handler: _GetCoreSchemaHandler) -> core_schema.CoreSchema:
Expand All @@ -61,6 +142,40 @@ def __get_pydantic_core_schema__(self, source_type: Any, handler: _GetCoreSchema

@_internal_dataclass.slots_dataclass(frozen=True)
class WrapValidator:
"""A metadata class that indicates that a validation should be applied **around** the inner validation logic.
```py
from datetime import datetime
from typing import Annotated
from pydantic import BaseModel, ValidationError, WrapValidator
def validate_timestamp(v, handler):
if v == "now":
# we don't want to bother with further validation, just return the new value
return datetime.now()
try:
return handler(v)
except ValidationError:
# validation failed, in this case we want to return a default value
return datetime(2000, 1, 1)
MyTimestamp = Annotated[datetime, WrapValidator(validate_timestamp)]
class Model(BaseModel):
a: MyTimestamp
print(Model(a="now").a)
# > 2023-01-22 23:10:00.000000
print(Model(a="invalid").a)
# > 2000-01-01 00:00:00.000000
```
"""

func: core_schema.GeneralWrapValidatorFunction | core_schema.FieldWrapValidatorFunction

def __get_pydantic_core_schema__(self, source_type: Any, handler: _GetCoreSchemaHandler) -> core_schema.CoreSchema:
Expand Down

0 comments on commit 31a4ac3

Please sign in to comment.