Open ikriv opened 1 month ago
Would the use of dataclasses.asdict help in your case?
Related, possible dup: #213
Indeed, asdict
would probably work even better than deserialization, because it will keep the type conversions, e.g. datetime
will remain datetime
, and not a string. Not sure why I missed it, thanks for the idea!
But still, we would first deserialize to dataclass and then convert to dict, which is clearly not ideal for performance, especially for large data graphs.
And indeed, my request looks very similar to #213, thanks for checking! Do you recall what was the reason for not merging #213?
I converted legacy code that used dictionaries to use dataclasses. However, the conversion is not 100%, so the same type is sometimes represented as a dataclass, and sometimes as a dictionary.
In the new code path, I use
class_schema(MyType)().loads(input)
, it gives me the dataclass, and all is good. But in the old, not yet converted code paths, I either need to maintain legacy schema manually (bad), or I need a way to obtain an 'old style' marshmallow schema fromclsas_schema(MyType)
that produces a dictionary. I found only one reliable way to achieve that by usingloads()
and thendump()
:Needless to say, this is cumbersome and inefficient. A better solution would be to have an option to provide a class schema that does not override
load()
of the base schema, something along the lines of:dict_schema = class_schema(MyType, use_base_schema_load = True)
This would create a schema class that derives from the provided base schema (
marshmallow.Schema
by default), defines all necessary fields, but does not overrideload()
.Example code before conversion:
Then we convert
frequent_function()
to use dataclass, but we leaverare_function()
as is:PROPOSAL:
Let's have