SHARE
TWEET

Untitled

a guest Oct 15th, 2019 78 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from dataclasses import dataclass
  2. from dataclasses_json import dataclass_json
  3. from datetime import datetime
  4. from typing import Optional
  5.  
  6. @dataclass_json
  7. @dataclass
  8. class FirstExample:
  9.     some_field: str
  10.     some_date: datetime
  11.    
  12.  
  13. right_now = datetime.now()
  14.  
  15. a = FirstExample(some_field="Hello", some_date=right_now)
  16. # this works as expected:
  17. print(FirstExample.schema().dumps(a))
  18.  
  19. # now, let's make one with an optional and default argument:
  20.  
  21. @dataclass_json
  22. @dataclass
  23. class SecondExample:
  24.     some_field: str
  25.     first_date: datetime
  26.     second_date: Optional[datetime] = None
  27.    
  28.  
  29. b = SecondExample(some_field="Hello", first_date=right_now, second_date=None)
  30.  
  31. # this will work:
  32. print(b.to_json())
  33.  
  34. # this will not:
  35. print(SecondExample.schema().dumps(b))
  36.  
  37. # > python small_example.py
  38. # {"some_date": 1569545970.938367, "some_field": "Hello"}
  39. # {"some_field": "Hello", "first_date": 1569545970.938367, "second_date": null}
  40. # Traceback (most recent call last):
  41. #   File "small_example.py", line 35, in <module>
  42. #     print(SecondExample.schema().dumps(b))
  43. #   File "/Users/bedricks/.pyenv/versions/3.7.2/lib/python3.7/site-packages/dataclasses_json/mm.py", line 292, in dumps
  44. #     return Schema.dumps(self, *args, **kwargs)
  45. #   File "/Users/bedricks/.pyenv/versions/3.7.2/lib/python3.7/site-packages/marshmallow/schema.py", line 583, in dumps
  46. #     serialized = self.dump(obj, many=many)
  47. #   File "/Users/bedricks/.pyenv/versions/3.7.2/lib/python3.7/site-packages/marshmallow/schema.py", line 553, in dump
  48. #     result = self._serialize(processed_obj, many=many)
  49. #   File "/Users/bedricks/.pyenv/versions/3.7.2/lib/python3.7/site-packages/marshmallow/schema.py", line 517, in _serialize
  50. #     value = field_obj.serialize(attr_name, obj, accessor=self.get_attribute)
  51. #   File "/Users/bedricks/.pyenv/versions/3.7.2/lib/python3.7/site-packages/marshmallow/fields.py", line 325, in serialize
  52. #     return self._serialize(value, attr, obj, **kwargs)
  53. #   File "/Users/bedricks/.pyenv/versions/3.7.2/lib/python3.7/site-packages/dataclasses_json/mm.py", line 26, in _serialize
  54. #     return value.timestamp()
  55. # AttributeError: 'NoneType' object has no attribute 'timestamp'
  56. # >
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top