Python jsons library and serializing a dataclass with optional None values

46 views Asked by At

I noticed some warning messages being printed by my Python code. These are coming from the jsons library when trying to perform serializing operations.

/home/user/project/.venv/lib/python3.11/site-packages/jsons/_common_impl.py:43: UserWarning: Failed to dump attribute "None" of object of type "MyClass2". Reason: 'NoneType' object is not callable. Ignoring the attribute. Use suppress_warning(attribute-not-serialized) or suppress_warnings(True) to turn off this message.
  warnings.warn(msg_, *args, **kwargs)

MyClass2 is just something I have been using to isolate the cause of the error.

class MyClass():

    def __init__(self) -> None:
        self.data = None

@dataclass
class MyClass2():
    data: int|None

my_class = MyClass()
my_class_2 = MyClass2(
    data=None,
)

print(
    jsons.dumps(
        my_class,
        strip_privates=True,
    )
)

print(
    jsons.dumps(
        my_class_2,
        strip_privates=True,
    )
)

MyClass does not produce warnings. MyClass2 does.

I know how to stop the warning message: Change the type hint from int|None to int.

@dataclass
class MyClass2():
    data: int     # no `|None` here !

Why does that work?

If I change the type hint from int|None, it will still serialize correctly but the warnings are no longer produced. Serializing None also works, even without the option of None as a type hint.

1

There are 1 answers

0
FreelanceConsultant On

As pointed out by others in the comments, this does indeed appear to be a bug.

As a workaround, I would suggest making the value Optional.

from typing import Optional

class MyClass:

    data: Optional[int] = None