lidatong / dataclasses-json

Easily serialize Data Classes to and from JSON
MIT License
1.34k stars 150 forks source link

[BUG] TypeError: cannot pickle '..' - despite being excluded #531

Open powellnorma opened 1 month ago

powellnorma commented 1 month ago

Description

Traceback (most recent call last):
  File "/tmp/test.py", line 38, in main
    print(t.to_json())
          ^^^^^^^^^^^
  File "/lib64/python3.11/site-packages/dataclasses_json/api.py", line 37, in to_json
    return json.dumps(self.to_dict(encode_json=False),
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/lib64/python3.11/site-packages/dataclasses_json/api.py", line 73, in to_dict
    return _asdict(self, encode_json=encode_json)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/lib64/python3.11/site-packages/dataclasses_json/core.py", line 417, in _asdict
    value = _asdict(
            ^^^^^^^^
  File "/lib64/python3.11/site-packages/dataclasses_json/core.py", line 439, in _asdict
    return copy.deepcopy(obj)
           ^^^^^^^^^^^^^^^^^^
  File "/usr/lib64/python3.11/copy.py", line 161, in deepcopy
    rv = reductor(4)
         ^^^^^^^^^^^
TypeError: cannot pickle '_asyncio.Task' object

Code snippet that reproduces the issue

@dataclass
class MyTask(DataClassJsonMixin):
    name: str
    task: asyncio.Task|None = field(default=None, metadata=config(exclude=lambda x:True))

async def main():
    t = MyTask("test", asyncio.create_task(asyncio.sleep(1)))
    print(t.to_json())

asyncio.run(main())

Describe the results you expected

I'd expect that it prints {name: "test"}

Python version you are using

Python 3.11.6

Environment description

dataclasses-json==0.6.6