cwacek/python-jsonschema-objects

deep-copying of instances seems not to work

rebcabin opened this issue · 0 comments

Here is a minimal viable example

import pytest
import fastjsonschema
import python_jsonschema_objects as pjs

from dataclasses import dataclass
import json
import copy
import pprint
pp = pprint.PrettyPrinter(indent=2)

lpid_class_schema = {
    '$id': 'https://example.com/schema-repository/lpid',
    '$schema': 'http://json-schema.org/draft-07/schema/#',
    'type': 'object',
    'title': 'Logical Process ID',
    'properties': {'lpid_str': {'type': 'string',}},
    'required': ['lpid_str'],
    'additionalProperties': True}


@dataclass()
class A:
    a_str: str


def test_pjs_deepcopy():
    # Class building and instantiation work great and round-trip.
    lpid_class_builder = pjs.ObjectBuilder(lpid_class_schema)
    LPID = lpid_class_builder.classes.LogicalProcessId
    lpid = LPID(lpid_str='foobaz')
    instance = json.loads(lpid.serialize())
    fastjsonschema.validate(lpid_class_schema, instance)

    # But deep-copying with objects of generated classes doesn't terminate.
    with pytest.raises(RecursionError) as e_info:
        lpid_2 = copy.deepcopy(lpid)
    pp.pprint(e_info)

    # Deep-copying seems to work with instances of normal popos.
    a = A(a_str='barqux')
    assert a
    a_2 = copy.deepcopy(a)
    assert a_2
    assert a == a_2

EDIT: A workaround might be to create a new, deeply copied instance object from the serialized JSON. Not sure whether you have code to do that. Would be a lot of boilerplate to write for a bunch of classes.