OpenSemanticLab / osw-python

GNU Affero General Public License v3.0
3 stars 2 forks source link

Rework casting mechanics #52

Open simontaurus opened 4 months ago

simontaurus commented 4 months ago

Current state: robotController = robotModel.cast(RobotController, args)

Wish: robotController = RobotController(robotModel, args..) the would require to override the __init__ to accept another base model that is converted to a dict that is de-packed to the actual contructor __init__(Union[BaseModel, kwargs])

see also: https://stackoverflow.com/questions/71895185/convert-derived-class-to-base-class-in-python/77446717#77446717

LukasGold commented 4 months ago

Idea: Overwrite pydantic __init__ with:

__init__(*args, **kwargs):
    data = kwargs
    if len(args) > 1:
        raiseError("Only one positional argument is allowed!")
    elif isinstance(args[0], OswBaseModel):
        data = {**args[0].dict(), **kwargs}
    else:
         raiseError(f"Can't cast {type(args[0]} to {type(self)}!")
    super().__init__(**data)

Potential issue: Static code checking might be altered / validation might be corrupted

simontaurus commented 1 week ago

Potential issue: Static code checking might be altered / validation might be corrupted

validation not as long as we call the actual class constructor. Static code checking should work since the return type of the target class contructor is the target class