Created
September 27, 2019 01:00
-
-
Save stevenbedrick/d05970da1a21b60c3cd8fc421d37e90e to your computer and use it in GitHub Desktop.
Small worked example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dataclasses import dataclass | |
from dataclasses_json import dataclass_json | |
from datetime import datetime | |
from typing import Optional | |
@dataclass_json | |
@dataclass | |
class FirstExample: | |
some_field: str | |
some_date: datetime | |
right_now = datetime.now() | |
a = FirstExample(some_field="Hello", some_date=right_now) | |
# this works as expected: | |
print(FirstExample.schema().dumps(a)) | |
# now, let's make one with an optional and default argument: | |
@dataclass_json | |
@dataclass | |
class SecondExample: | |
some_field: str | |
first_date: datetime | |
second_date: Optional[datetime] = None | |
b = SecondExample(some_field="Hello", first_date=right_now, second_date=None) | |
# this will work: | |
print(b.to_json()) | |
# this will not: | |
print(SecondExample.schema().dumps(b)) | |
# > python small_example.py | |
# {"some_date": 1569545970.938367, "some_field": "Hello"} | |
# {"some_field": "Hello", "first_date": 1569545970.938367, "second_date": null} | |
# Traceback (most recent call last): | |
# File "small_example.py", line 35, in <module> | |
# print(SecondExample.schema().dumps(b)) | |
# File "/Users/bedricks/.pyenv/versions/3.7.2/lib/python3.7/site-packages/dataclasses_json/mm.py", line 292, in dumps | |
# return Schema.dumps(self, *args, **kwargs) | |
# File "/Users/bedricks/.pyenv/versions/3.7.2/lib/python3.7/site-packages/marshmallow/schema.py", line 583, in dumps | |
# serialized = self.dump(obj, many=many) | |
# File "/Users/bedricks/.pyenv/versions/3.7.2/lib/python3.7/site-packages/marshmallow/schema.py", line 553, in dump | |
# result = self._serialize(processed_obj, many=many) | |
# File "/Users/bedricks/.pyenv/versions/3.7.2/lib/python3.7/site-packages/marshmallow/schema.py", line 517, in _serialize | |
# value = field_obj.serialize(attr_name, obj, accessor=self.get_attribute) | |
# File "/Users/bedricks/.pyenv/versions/3.7.2/lib/python3.7/site-packages/marshmallow/fields.py", line 325, in serialize | |
# return self._serialize(value, attr, obj, **kwargs) | |
# File "/Users/bedricks/.pyenv/versions/3.7.2/lib/python3.7/site-packages/dataclasses_json/mm.py", line 26, in _serialize | |
# return value.timestamp() | |
# AttributeError: 'NoneType' object has no attribute 'timestamp' | |
# > |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment