Skip to content

Commit 3fea833

Browse files
Fix bug re custom_init on members of Union (#1076)
1 parent 73b1184 commit 3fea833

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

src/validators/model.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,10 @@ impl ModelValidator {
257257
// this work with from_attributes, and would essentially allow you to
258258
// handle init vars by adding them to the __init__ signature.
259259
if let Some(kwargs) = input.as_kwargs(py) {
260-
return Ok(self.class.call(py, (), Some(kwargs))?);
260+
return self
261+
.class
262+
.call(py, (), Some(kwargs))
263+
.map_err(|e| convert_err(py, e, input));
261264
}
262265
}
263266

tests/validators/test_model_init.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -479,3 +479,48 @@ def _wrap_validator(cls, v, validator, info):
479479
gc.collect()
480480

481481
assert ref() is None
482+
483+
484+
def test_model_custom_init_with_union() -> None:
485+
class A:
486+
def __init__(self, **kwargs):
487+
assert 'a' in kwargs
488+
self.a = kwargs.get('a')
489+
490+
class B:
491+
def __init__(self, **kwargs):
492+
assert 'b' in kwargs
493+
self.b = kwargs.get('b')
494+
495+
schema = {
496+
'type': 'union',
497+
'choices': [
498+
{
499+
'type': 'model',
500+
'cls': A,
501+
'schema': {
502+
'type': 'model-fields',
503+
'fields': {'a': {'type': 'model-field', 'schema': {'type': 'bool'}}},
504+
'model_name': 'A',
505+
},
506+
'custom_init': True,
507+
'ref': '__main__.A:4947206928',
508+
},
509+
{
510+
'type': 'model',
511+
'cls': B,
512+
'schema': {
513+
'type': 'model-fields',
514+
'fields': {'b': {'type': 'model-field', 'schema': {'type': 'bool'}}},
515+
'model_name': 'B',
516+
},
517+
'custom_init': True,
518+
'ref': '__main__.B:4679932848',
519+
},
520+
],
521+
}
522+
523+
validator = SchemaValidator(schema)
524+
525+
assert validator.validate_python({'a': False}).a is False
526+
assert validator.validate_python({'b': True}).b is True

0 commit comments

Comments
 (0)