@@ -312,7 +312,7 @@ def _get_discriminator_attribute(cls) -> Optional['DiscriminatorAttribute']:
312
312
def _set_discriminator (self ) -> None :
313
313
discriminator_attr = self ._get_discriminator_attribute ()
314
314
if discriminator_attr and discriminator_attr .get_discriminator (self .__class__ ) is not None :
315
- self . attribute_values [ self ._discriminator ] = self .__class__ # type: ignore
315
+ setattr ( self , self ._discriminator , self .__class__ ) # type: ignore
316
316
317
317
def _set_defaults (self , _user_instantiated : bool = True ) -> None :
318
318
"""
@@ -371,18 +371,22 @@ def deserialize(self, attribute_values: Dict[str, Dict[str, Any]]) -> None:
371
371
setattr (self , name , value )
372
372
373
373
@classmethod
374
- def _instantiate (cls : Type [ _ACT ] , attribute_values : Dict [str , Dict [str , Any ]]) -> _ACT :
374
+ def _get_discriminator_class (cls , attribute_values : Dict [str , Dict [str , Any ]]) -> Optional [ Type ] :
375
375
discriminator_attr = cls ._get_discriminator_attribute ()
376
376
if discriminator_attr :
377
- discriminator_attribute_value = attribute_values .pop (discriminator_attr .attr_name , None )
377
+ discriminator_attribute_value = attribute_values .get (discriminator_attr .attr_name , None )
378
378
if discriminator_attribute_value :
379
379
discriminator_value = discriminator_attr .get_value (discriminator_attribute_value )
380
- stored_cls = discriminator_attr .deserialize (discriminator_value )
381
- if not issubclass (stored_cls , cls ):
382
- raise ValueError ("Cannot instantiate a {} from the returned class: {}" .format (
383
- cls .__name__ , stored_cls .__name__ ))
384
- cls = stored_cls
385
- instance = cls (_user_instantiated = False )
380
+ return discriminator_attr .deserialize (discriminator_value )
381
+ return None
382
+
383
+ @classmethod
384
+ def _instantiate (cls : Type [_ACT ], attribute_values : Dict [str , Dict [str , Any ]]) -> _ACT :
385
+ stored_cls = cls ._get_discriminator_class (attribute_values )
386
+ if stored_cls and not issubclass (stored_cls , cls ):
387
+ raise ValueError ("Cannot instantiate a {} from the returned class: {}" .format (
388
+ cls .__name__ , stored_cls .__name__ ))
389
+ instance = (stored_cls or cls )(_user_instantiated = False )
386
390
AttributeContainer .deserialize (instance , attribute_values )
387
391
return instance
388
392
@@ -422,7 +426,9 @@ def get_discriminator(self, cls: type) -> Optional[Any]:
422
426
return self ._class_map .get (cls )
423
427
424
428
def __set__ (self , instance : Any , value : Optional [type ]) -> None :
425
- raise TypeError ("'{}' object does not support item assignment" .format (self .__class__ .__name__ ))
429
+ if type (instance ) != value :
430
+ raise ValueError ("The discriminator attribute must be set to the instance type: {}" .format (type (instance )))
431
+ super ().__set__ (instance , value )
426
432
427
433
def serialize (self , value ):
428
434
"""
0 commit comments