From 0bc40cf248f3d43c5781a0b8ea6b4f199437f76d Mon Sep 17 00:00:00 2001 From: Mark Pilgrim Date: Wed, 23 Sep 2009 08:44:24 -0400 Subject: [PATCH] back to more descriptive TypeError --- examples/customserializer.py | 2 +- publish | 3 +++ serializing.html | 4 ++-- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/examples/customserializer.py b/examples/customserializer.py index 19cae8f..e23ebb4 100644 --- a/examples/customserializer.py +++ b/examples/customserializer.py @@ -9,7 +9,7 @@ def to_json(python_object): if isinstance(python_object, bytes): return {'__class__': 'bytes', '__value__': list(python_object)} - raise TypeError + raise TypeError(repr(python_object) + ' is not JSON serializable') def from_json(json_object): if '__class__' in json_object: diff --git a/publish b/publish index b0f4f46..d2e234b 100755 --- a/publish +++ b/publish @@ -8,6 +8,9 @@ die () { echo "started build" +# build table of contents +python3 util/buildtoc.py + revision=`hg tip | grep changeset|cut -d":" -f2|cut -d" " -f4` today=`date +"%Y-%m-%d"` diff --git a/serializing.html b/serializing.html index eba5fed..e81a674 100644 --- a/serializing.html +++ b/serializing.html @@ -457,7 +457,7 @@ def protocol_version(file_object): if isinstance(python_object, bytes): return {'__class__': 'bytes', '__value__': list(python_object)} - raise TypeError + raise TypeError(repr(python_object) + ' is not JSON serializable')
  1. To define your own “mini-serialization format” for a datatype that JSON doesn’t support natively, just define a function that takes a Python object as a parameter. This Python object will be the actual object that the json.dump() function is unable to serialize by itself — in this case, the bytes object b'\xDE\xD5\xB4\xF8'.
  2. Your custom serialization function should check the type of the Python object that the json.dump() function passed to it. This is not strictly necessary if your function only serializes one datatype, but it makes it crystal clear what case your function is covering, and it makes it easier to extend if you need to add serializations for more datatypes later. @@ -507,7 +507,7 @@ def to_json(python_object): if isinstance(python_object, bytes): return {'__class__': 'bytes', '__value__': list(python_object)} - raise TypeError + raise TypeError(repr(python_object) + ' is not JSON serializable')
    1. Adding to our existing customserializer.to_json() function, we need to check whether the Python object (that the json.dump() function is having trouble with) is a time.struct_time.
    2. If so, we’ll do something similar to the conversion we did with the bytes object: convert the time.struct_time object to a dictionary that only contains JSON-serializable values. In this case, the easiest way to convert a datetime into a JSON-serializable value is to convert it to a string with the time.asctime() function. The time.asctime() function will convert that nasty-looking time.struct_time into the string 'Fri Mar 27 22:20:42 2009'.