Issue when using dataclass with InitVar fields
See original GitHub issueDescription
If we have a dataclass with init var field
model_schema().load()
is not working properly
Steps to reproduce
import json
import unittest
from dataclasses import dataclass, field, InitVar
from typing import Any, Dict
import marshmallow_dataclass
@dataclass
class Sample:
welcome_message: str = field(init=False)
name: InitVar[str]
def __post_init__(self,
name: str
) -> None:
self.welcome_message = f"Welcome {name}"
def as_json_string(self):
return json.dumps(self, default=lambda o: o.__dict__)
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> 'Sample':
model_schema = marshmallow_dataclass.class_schema(cls)
return model_schema().load(data)
class TestModel(unittest.TestCase):
def test_json_to_object_to_json(self):
test = Sample("John")
test_to_json = json.loads(test.as_json_string())
print(test_to_json)
print(test)
self.assertEqual(test, Sample.from_dict(test_to_json))
if __name__ == '__main__':
unittest.main()
Error is
marshmallow.exceptions.ValidationError: {'welcome_message': ['Unknown field.']}
Issue Analytics
- State:
- Created 3 years ago
- Comments:5 (2 by maintainers)
Top Results From Across the Web
How do I get Python dataclass InitVar fields to work with typing ...
The issue, at least from the surface, seems to be with InitVar and with how typing.get_type_hints resolves such non-generic types.
Read more >Default value for InitVar fields on dataclasses #174 - GitHub
The mechanism for dataclasses to recognize InitVar types seems to inspect the type of the field. ... roeap opened this issue on Jul...
Read more >dataclasses — Data Classes — Python 3.11.1 documentation
If a field is an InitVar , it is considered a pseudo-field called an init-only field. As it is not a true field,...
Read more >How to use the dataclasses.InitVar function in dataclasses | Snyk
Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues...
Read more >Overwriting init-only fields in dataclasses causes to ... - YouTrack
Visible to issue readers ... from dataclasses import dataclass, InitVar @dataclass class Node: nodeId: str sourceData: InitVar[dict] @dataclass class ...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
@scoulomb : isn’t this a duplicate of #83 ?
OK, closing as a duplicate of #83
We can continue the discussion there