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

feat: pass config to NamedTuple fields #4225

Merged
merged 3 commits into from Aug 8, 2022
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/4219-synek.md
@@ -0,0 +1 @@
Use parent model's `Config` when validating nested `NamedTuple` fields.
7 changes: 5 additions & 2 deletions pydantic/validators.py
Expand Up @@ -555,11 +555,14 @@ def pattern_validator(v: Any) -> Pattern[str]:
NamedTupleT = TypeVar('NamedTupleT', bound=NamedTuple)


def make_namedtuple_validator(namedtuple_cls: Type[NamedTupleT]) -> Callable[[Tuple[Any, ...]], NamedTupleT]:
def make_namedtuple_validator(
namedtuple_cls: Type[NamedTupleT], config: Type['BaseConfig']
) -> Callable[[Tuple[Any, ...]], NamedTupleT]:
from .annotated_types import create_model_from_namedtuple

NamedTupleModel = create_model_from_namedtuple(
namedtuple_cls,
__config__=config,
__module__=namedtuple_cls.__module__,
)
namedtuple_cls.__pydantic_model__ = NamedTupleModel # type: ignore[attr-defined]
Expand Down Expand Up @@ -690,7 +693,7 @@ def find_validators( # noqa: C901 (ignore complexity)
return
if is_namedtuple(type_):
yield tuple_validator
yield make_namedtuple_validator(type_)
yield make_namedtuple_validator(type_, config)
return
if is_typeddict(type_):
yield make_typeddict_validator(type_, config)
Expand Down
23 changes: 23 additions & 0 deletions tests/test_annotated_types.py
Expand Up @@ -146,6 +146,29 @@ class Model(BaseModel):
Model.parse_obj({'t': [-1]})


def test_namedtuple_arbitrary_type():
class CustomClass:
pass

class Tup(NamedTuple):
c: CustomClass

class Model(BaseModel):
x: Tup

class Config:
arbitrary_types_allowed = True

data = {'x': Tup(c=CustomClass())}
model = Model.parse_obj(data)
assert isinstance(model.x.c, CustomClass)

with pytest.raises(RuntimeError):

hramezani marked this conversation as resolved.
Show resolved Hide resolved
class ModelNoArbitraryTypes(BaseModel):
x: Tup


def test_typeddict():
class TD(TypedDict):
a: int
Expand Down