question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Issue when using dataclass with InitVar fields

See original GitHub issue

Description

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:closed
  • Created 3 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
lovasoacommented, Jun 5, 2020

@scoulomb : isn’t this a duplicate of #83 ?

0reactions
lovasoacommented, Jun 5, 2020

OK, closing as a duplicate of #83

We can continue the discussion there

Read more comments on GitHub >

github_iconTop 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 >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found