def test_python_object_encoder_unpicklable(self): class CannotPickleThis: """Da na na na. Can't pickle this. """ def __init__(self): self.x = 1 obj = [1, CannotPickleThis()] expected_obj = [1, UnpicklableObject()] with self.assertRaises(ValueError): dumps = json.dumps(obj, indent=4, sort_keys=True, cls=define_python_object_encoder()) dumps = json.dumps(obj, indent=4, sort_keys=True, cls=define_python_object_encoder(True)) recreated_obj = json.loads(dumps, object_hook=as_python_object) self.assertEqual(recreated_obj, expected_obj)
def test_python_object_encoder_simple_types(self): obj = [1, 2, 'hi', 'bye', 7.3, [1, 2, 'blarg'], True, False, None] dumps = json.dumps(obj, indent=4, sort_keys=True, cls=define_python_object_encoder()) recreated_obj = json.loads(dumps, object_hook=as_python_object) self.assertEqual(recreated_obj, obj)
def save(self, path: str, with_reproducibility: bool = True, skip_unpicklable: bool = False) -> None: """Saves the arguments and reproducibility information in JSON format, pickling what can't be encoded. :param path: Path to the JSON file where the arguments will be saved. :param with_reproducibility: If True, adds a "reproducibility" field with information (e.g. git hash) to the JSON file. :param skip_unpicklable: If True, does not save attributes whose values cannot be pickled. """ with open(path, 'w') as f: args = self._log_all() if with_reproducibility else self.as_dict() json.dump(args, f, indent=4, sort_keys=True, cls=define_python_object_encoder(skip_unpicklable))
def test_python_object_encoder_complex(self): obj = [ 1, 2, 'hi', 'bye', 7.3, {1, 2, 'blarg'}, [('hi', 'bye'), 2], { 'hi': { 'bye': {3, 4} } }, True, False, None, (Person('tappy'), Person('tapper')) ] dumps = json.dumps(obj, indent=4, sort_keys=True, cls=define_python_object_encoder()) recreated_obj = json.loads(dumps, object_hook=as_python_object) self.assertEqual(recreated_obj, obj)
def test_python_object_encoder_set(self): obj = [ 1, 2, 'hi', 'bye', 7.3, {1, 2, 'blarg'}, [{'hi', 'bye'}, 2], { 'hi': { 'bye': {3, 4} } }, True, False, None ] dumps = json.dumps(obj, indent=4, sort_keys=True, cls=define_python_object_encoder()) recreated_obj = json.loads(dumps, object_hook=as_python_object) self.assertEqual(recreated_obj, obj)