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

Prevent mutation of excludes/includes #1404

Merged
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
1 change: 1 addition & 0 deletions changes/1404-AlexECX.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Make includes/excludes arguments for `.dict()`, `._iter()`, ..., immutable.
31 changes: 16 additions & 15 deletions pydantic/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
Callable,
Dict,
List,
Mapping,
Optional,
Tuple,
Type,
Expand Down Expand Up @@ -49,7 +50,7 @@
from .class_validators import ValidatorListDict
from .types import ModelOrDc
from .typing import CallableGenerator, TupleGenerator, DictStrAny, DictAny, SetStr
from .typing import AbstractSetIntStr, DictIntStrAny, ReprArgs # noqa: F401
from .typing import AbstractSetIntStr, MappingIntStrAny, ReprArgs # noqa: F401

ConfigType = Type['BaseConfig']
Model = TypeVar('Model', bound='BaseModel')
Expand Down Expand Up @@ -363,8 +364,8 @@ def __setstate__(self, state: 'DictAny') -> None:
def dict(
self,
*,
include: Union['AbstractSetIntStr', 'DictIntStrAny'] = None,
exclude: Union['AbstractSetIntStr', 'DictIntStrAny'] = None,
include: Union['AbstractSetIntStr', 'MappingIntStrAny'] = None,
exclude: Union['AbstractSetIntStr', 'MappingIntStrAny'] = None,
by_alias: bool = False,
skip_defaults: bool = None,
exclude_unset: bool = False,
Expand Down Expand Up @@ -397,8 +398,8 @@ def dict(
def json(
self,
*,
include: Union['AbstractSetIntStr', 'DictIntStrAny'] = None,
exclude: Union['AbstractSetIntStr', 'DictIntStrAny'] = None,
include: Union['AbstractSetIntStr', 'MappingIntStrAny'] = None,
exclude: Union['AbstractSetIntStr', 'MappingIntStrAny'] = None,
by_alias: bool = False,
skip_defaults: bool = None,
exclude_unset: bool = False,
Expand Down Expand Up @@ -517,8 +518,8 @@ def construct(cls: Type['Model'], _fields_set: Optional['SetStr'] = None, **valu
def copy(
self: 'Model',
*,
include: Union['AbstractSetIntStr', 'DictIntStrAny'] = None,
exclude: Union['AbstractSetIntStr', 'DictIntStrAny'] = None,
include: Union['AbstractSetIntStr', 'MappingIntStrAny'] = None,
exclude: Union['AbstractSetIntStr', 'MappingIntStrAny'] = None,
update: 'DictStrAny' = None,
deep: bool = False,
) -> 'Model':
Expand Down Expand Up @@ -594,8 +595,8 @@ def _get_value(
v: Any,
to_dict: bool,
by_alias: bool,
include: Optional[Union['AbstractSetIntStr', 'DictIntStrAny']],
exclude: Optional[Union['AbstractSetIntStr', 'DictIntStrAny']],
include: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']],
exclude: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']],
exclude_unset: bool,
exclude_defaults: bool,
exclude_none: bool,
Expand Down Expand Up @@ -674,8 +675,8 @@ def _iter(
self,
to_dict: bool = False,
by_alias: bool = False,
include: Union['AbstractSetIntStr', 'DictIntStrAny'] = None,
exclude: Union['AbstractSetIntStr', 'DictIntStrAny'] = None,
include: Union['AbstractSetIntStr', 'MappingIntStrAny'] = None,
exclude: Union['AbstractSetIntStr', 'MappingIntStrAny'] = None,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
Expand Down Expand Up @@ -714,8 +715,8 @@ def _iter(

def _calculate_keys(
self,
include: Optional[Union['AbstractSetIntStr', 'DictIntStrAny']],
exclude: Optional[Union['AbstractSetIntStr', 'DictIntStrAny']],
include: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']],
exclude: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']],
exclude_unset: bool,
update: Optional['DictStrAny'] = None,
) -> Optional[AbstractSet[str]]:
Expand All @@ -729,7 +730,7 @@ def _calculate_keys(
keys = self.__dict__.keys()

if include is not None:
if isinstance(include, dict):
if isinstance(include, Mapping):
keys &= include.keys()
else:
keys &= include
Expand All @@ -738,7 +739,7 @@ def _calculate_keys(
keys -= update.keys()

if exclude:
if isinstance(exclude, dict):
if isinstance(exclude, Mapping):
keys -= {k for k, v in exclude.items() if v is ...}
else:
keys -= exclude
Expand Down
2 changes: 2 additions & 0 deletions pydantic/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
Dict,
Generator,
List,
Mapping,
NewType,
Optional,
Sequence,
Expand Down Expand Up @@ -72,6 +73,7 @@ def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Type[
IntStr = Union[int, str]
AbstractSetIntStr = AbstractSet[IntStr]
DictIntStrAny = Dict[IntStr, Any]
MappingIntStrAny = Mapping[IntStr, Any]
CallableGenerator = Generator[AnyCallable, None, None]
ReprArgs = Sequence[Tuple[Optional[str], Any]]

Expand Down
21 changes: 11 additions & 10 deletions pydantic/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
if TYPE_CHECKING:
from inspect import Signature
from .main import BaseModel, BaseConfig # noqa: F401
from .typing import AbstractSetIntStr, DictIntStrAny, IntStr, ReprArgs # noqa: F401
from .typing import AbstractSetIntStr, DictIntStrAny, IntStr, MappingIntStrAny, ReprArgs # noqa: F401
from .fields import ModelField # noqa: F401
from .dataclasses import DataclassType # noqa: F401

Expand Down Expand Up @@ -333,9 +333,9 @@ class ValueItems(Representation):

__slots__ = ('_items', '_type')

def __init__(self, value: Any, items: Union['AbstractSetIntStr', 'DictIntStrAny']) -> None:
def __init__(self, value: Any, items: Union['AbstractSetIntStr', 'MappingIntStrAny']) -> None:
if TYPE_CHECKING:
self._items: Union['AbstractSetIntStr', 'DictIntStrAny']
self._items: Union['AbstractSetIntStr', 'MappingIntStrAny']
self._type: Type[Union[set, dict]] # type: ignore

# For further type checks speed-up
Expand Down Expand Up @@ -380,7 +380,7 @@ def is_included(self, item: Any) -> bool:
return item in self._items

@no_type_check
def for_element(self, e: 'IntStr') -> Optional[Union['AbstractSetIntStr', 'DictIntStrAny']]:
def for_element(self, e: 'IntStr') -> Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']]:
"""
:param e: key or index of element on value
:return: raw values for elemet if self._items is dict and contain needed element
Expand All @@ -393,7 +393,7 @@ def for_element(self, e: 'IntStr') -> Optional[Union['AbstractSetIntStr', 'DictI

@no_type_check
def _normalize_indexes(
self, items: Union['AbstractSetIntStr', 'DictIntStrAny'], v_length: int
self, items: Union['AbstractSetIntStr', 'MappingIntStrAny'], v_length: int
) -> Union['AbstractSetIntStr', 'DictIntStrAny']:
"""
:param items: dict or set of indexes which will be normalized
Expand All @@ -411,12 +411,13 @@ def _normalize_indexes(
return {i for i in range(v_length)}
return {v_length + i if i < 0 else i for i in items}
else:
if '__all__' in items:
all_set = items.pop('__all__')
normalized_items = {v_length + i if i < 0 else i: v for i, v in items.items() if i != '__all__'}
all_set = items.get('__all__')
if all_set:
for i in range(v_length):
iset = items.setdefault(i, set())
iset.update(all_set)
return {v_length + i if i < 0 else i: v for i, v in items.items()}
normalized_items.setdefault(i, set()).update(all_set)

return normalized_items

def __repr_args__(self) -> 'ReprArgs':
return [(None, self._items)]
12 changes: 9 additions & 3 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -1011,9 +1011,15 @@ class Foo(BaseModel):

m = Foo(a=1, bars=[{'w': 0, 'x': 1}, {'y': 2}, {'w': -1, 'z': 3}])

assert m.dict(exclude={'bars': {0}}) == {'a': 1, 'bars': [{'y': 2}, {'w': -1, 'z': 3}]}
assert m.dict(exclude={'bars': {'__all__'}}) == {'a': 1, 'bars': []}
assert m.dict(exclude={'bars': {'__all__': {'w'}}}) == {'a': 1, 'bars': [{'x': 1}, {'y': 2}, {'z': 3}]}
excludes = {'bars': {0}}
assert m.dict(exclude=excludes) == {'a': 1, 'bars': [{'y': 2}, {'w': -1, 'z': 3}]}
assert excludes == {'bars': {0}}
excludes = {'bars': {'__all__'}}
assert m.dict(exclude=excludes) == {'a': 1, 'bars': []}
assert excludes == {'bars': {'__all__'}}
excludes = {'bars': {'__all__': {'w'}}}
assert m.dict(exclude=excludes) == {'a': 1, 'bars': [{'x': 1}, {'y': 2}, {'z': 3}]}
assert excludes == {'bars': {'__all__': {'w'}}}


def test_custom_init_subclass_params():
Expand Down