schrodinger.models.json module¶
This is a module that extends Python’s standard builtin json module. It offers the following additional features:
JsonableClassMixin
, a mixin that helps with creating serializable classes- An extended JSON encoder that can handle classes derived from
JsonableClassMixin
dump
anddumps
functions that use the extended encoder by default.
-
exception
schrodinger.models.json.
JSONDecodeError
¶ Bases:
ValueError
-
__init__
¶ Initialize self. See help(type(self)) for accurate signature.
-
args
¶
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
-
exception
schrodinger.models.json.
JSONEncodeError
¶ Bases:
ValueError
-
__init__
¶ Initialize self. See help(type(self)) for accurate signature.
-
args
¶
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
-
class
schrodinger.models.json.
AttributableType
¶ Bases:
list
-
__contains__
¶ Return key in self.
-
__init__
¶ Initialize self. See help(type(self)) for accurate signature.
-
__len__
¶ Return len(self).
-
append
(object) → None -- append object to end¶
-
clear
() → None -- remove all items from L¶
-
copy
() → list -- a shallow copy of L¶
-
count
(value) → integer -- return number of occurrences of value¶
-
extend
(iterable) → None -- extend list by appending elements from the iterable¶
-
index
(value[, start[, stop]]) → integer -- return first index of value.¶ Raises ValueError if the value is not present.
-
insert
()¶ L.insert(index, object) – insert object before index
-
pop
([index]) → item -- remove and return item at index (default last).¶ Raises IndexError if list is empty or index is out of range.
-
remove
(value) → None -- remove first occurrence of value.¶ Raises ValueError if the value is not present.
-
reverse
()¶ L.reverse() – reverse IN PLACE
-
sort
(key=None, reverse=False) → None -- stable sort *IN PLACE*¶
-
-
class
schrodinger.models.json.
JsonableClassMixin
¶ Bases:
object
A mixin that aids in making a class Jsonable. Users must define
toJsonImplementation(self)
andfromJsonImplementation(cls, json_dict)
. For example:class Person(JsonableClassMixin, object): def __init__(self, full_name, age): self.full_name = full_name self.age = age def toJsonImplementation(self): return {'full_name':self.full_name, 'age':self.age} @classmethod def fromJsonImplementation(cls, json_dict): return cls(json_dict['full_name'], json_dict['age'])
Now
dump
anddumps
can encodePerson
:# Encode to a file abe = Person('Abraham Lincoln', 208) with open('abe.json', 'w') as out_file: json.dump(abe, out_file) # Encode to a string abe_json_string = json.dumps(abe)
If you want to decode the json string or file, you’ll have to use
loads
orload
and then feed in the result to your class’ public class methodfromJson()
:# Loading an object from a json file with open('abe.json', 'r') as in_file: abe_json = json.load(in_file) abe = Person.fromJson(abe_json) # Loading an object from a json string abe_json = json.loads(abe_json_string) abe = Person.fromJson(abe_json)
-
toJsonImplementation
()¶ Abstract method that must be defined by all derived classes. Converts an instance of the derived class into a jsonifiable object.
Returns: A dict made up of JSON native datatypes or Jsonable objects. See the link below for a table of such types. https://docs.python.org/2/library/json.html#encoders-and-decoders
-
classmethod
fromJsonImplementation
(json_dict)¶ Abstract method that must be defined by all derived classes. Takes in a dictionary and constructs an instance of the derived class.
Parameters: json_dict (dict) – A dictionary loaded from a JSON string or file. Returns: An instance of the derived class. :rtype : cls
-
toJson
(_mark_version=True)¶ Create and returns a data structure made up of jsonable items.
Return type: An instance of one the classes from NATIVE_JSON_DATATYPES
-
classmethod
fromJson
(json_obj)¶ A factory method which constructs a new object from a given dict loaded from a json string or file.
Parameters: json_obj (dict) – A json-loaded dictionary to create an object from. Returns: An instance of this class. :rtype : cls
-
get_version
()¶ Method to get the version of a particular object. Defaults to the current version of mmshare. This class can be overridden for custom versioning behavior.
-
__init__
¶ Initialize self. See help(type(self)) for accurate signature.
-
-
schrodinger.models.json.
adapter
(version)¶ This function is a decorator used to define an adapter function that takes in a
json_obj
from an older version of aJsonableClassMixin
and returns it modified such that it can be read in by the version of the class specified by theversion
argument (typically the current version at the time the adapter is written).As a example, imagine we define a simple class:
class Person: # mmshare version: 40000 def __init__(self, full_name): self.full_name = full_name
If, in mmshare version 41000, we split
full_name
into attributesfirst_name
andlast_name
, we could define an adapter like so:class Person: # mmshare version: 41000 def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name @json.adapter(version=41000) def _JsonAdapter(self, json_dict): full_name = json_dict.pop(full_name) fname, lname = full_name.split(' ') json_dict['first_name'] = fname json_dict['last_name'] = lname return json_dict
Note
An adapter function only needs to bring the
json_dict
up-to-date with the class at the time that the adapter is written. The next time the class is changed in a way that breaks json decoding, a new adapter function should be added to the class that takes in the previous adapter’s output and makes it compatible with the current class. In this way the json framework can decode any older version by automatically passing it through the appropriate chain of adapter functions.Parameters: version (int, str, or list of str or ints) – The data version to which an older json_dict
will be adapted (typically the current version when the adapter is writte).Raises: TypeError – if version
is not an int, str, or list
-
schrodinger.models.json.
dumps
(obj, **kwargs)¶ A wrapper that automatically encodes objects derived from
JsonableClassMixin
.If
obj
does not subclassJsonableClassMixin
, then this function will behave exactly like the builtinjson.dumps
.
-
schrodinger.models.json.
dump
(obj, fp, **kwargs)¶ A wrapper that automatically encodes objects derived from
JsonableClassMixin
.If
obj
does not subclassJsonableClassMixin
, then this function will behave exactly like the builtinjson.dump
.
-
schrodinger.models.json.
loads
(json_str, DataClass=None, **kwargs)¶ A wrapper that automatically decodes json strings serialized from
JsonableClassMixin
objects.param DataClass: The class of the object that was serialized into json_str
. This can be optionally specified to save an extra step if the object was serialized usingJsonableClassMixin
.If the json string was not an encoded
JsonableClassMixin
object, this function will behave exactly like the builtinjson.loads
.
-
schrodinger.models.json.
load
(fp, DataClass=None, **kwargs)¶ A wrapper that automatically decodes json files serialized from
JsonableClassMixin
objects.param DataClass: The class of the object that was serialized into json_str
. This can be optionally specified to save an extra step if the object was serialized usingJsonableClassMixin
.If the json file was not an encoded
JsonableClassMixin
object, this function will behave exactly like the builtinjson.load
.
-
class
schrodinger.models.json.
JsonableEnum
(*args, **kwargs)¶ Bases:
schrodinger.models.json._JsonableEnumBase
,enum.Enum
An enumeration.
-
__init__
(*args, **kwargs)¶ Initialize self. See help(type(self)) for accurate signature.
-
fromJsonImplementation
= <bound method JsonableEnum.fromJsonImplementation of <enum 'JsonableEnum'>>¶
-
toJsonImplementation
()¶ Abstract method that must be defined by all derived classes. Converts an instance of the derived class into a jsonifiable object.
Returns: A dict made up of JSON native datatypes or Jsonable objects. See the link below for a table of such types. https://docs.python.org/2/library/json.html#encoders-and-decoders
-
-
class
schrodinger.models.json.
JsonableIntEnum
(*args, **kwargs)¶ Bases:
int
,schrodinger.models.json.JsonableClassMixin
,enum.Enum
An enumeration.
-
__init__
(*args, **kwargs)¶ Initialize self. See help(type(self)) for accurate signature.
-
fromJsonImplementation
= <bound method JsonableIntEnum.fromJsonImplementation of <enum 'JsonableIntEnum'>>¶
-
toJsonImplementation
()¶ Abstract method that must be defined by all derived classes. Converts an instance of the derived class into a jsonifiable object.
Returns: A dict made up of JSON native datatypes or Jsonable objects. See the link below for a table of such types. https://docs.python.org/2/library/json.html#encoders-and-decoders
-
-
class
schrodinger.models.json.
JsonableSet
¶ Bases:
schrodinger.models.json.JsonableClassMixin
,set
-
ENCODING_KEY
= '_python_set_'¶
-
toJsonImplementation
()¶ Abstract method that must be defined by all derived classes. Converts an instance of the derived class into a jsonifiable object.
Returns: A dict made up of JSON native datatypes or Jsonable objects. See the link below for a table of such types. https://docs.python.org/2/library/json.html#encoders-and-decoders
-
classmethod
fromJsonImplementation
(json_list)¶ Abstract method that must be defined by all derived classes. Takes in a dictionary and constructs an instance of the derived class.
Parameters: json_dict (dict) – A dictionary loaded from a JSON string or file. Returns: An instance of the derived class. :rtype : cls
-
copy
()¶ Return a shallow copy of a set.
-
__contains__
()¶ x.__contains__(y) <==> y in x.
-
__init__
¶ Initialize self. See help(type(self)) for accurate signature.
-
__len__
¶ Return len(self).
-
add
()¶ Add an element to a set.
This has no effect if the element is already present.
-
clear
()¶ Remove all elements from this set.
-
difference
()¶ Return the difference of two or more sets as a new set.
(i.e. all elements that are in this set but not the others.)
-
difference_update
()¶ Remove all elements of another set from this set.
-
discard
()¶ Remove an element from a set if it is a member.
If the element is not a member, do nothing.
-
classmethod
fromJson
(json_obj)¶ A factory method which constructs a new object from a given dict loaded from a json string or file.
Parameters: json_obj (dict) – A json-loaded dictionary to create an object from. Returns: An instance of this class. :rtype : cls
-
get_version
()¶ Method to get the version of a particular object. Defaults to the current version of mmshare. This class can be overridden for custom versioning behavior.
-
intersection
()¶ Return the intersection of two sets as a new set.
(i.e. all elements that are in both sets.)
-
intersection_update
()¶ Update a set with the intersection of itself and another.
-
isdisjoint
()¶ Return True if two sets have a null intersection.
-
issubset
()¶ Report whether another set contains this set.
-
issuperset
()¶ Report whether this set contains another set.
-
pop
()¶ Remove and return an arbitrary set element. Raises KeyError if the set is empty.
-
remove
()¶ Remove an element from a set; it must be a member.
If the element is not a member, raise a KeyError.
-
symmetric_difference
()¶ Return the symmetric difference of two sets as a new set.
(i.e. all elements that are in exactly one of the sets.)
-
symmetric_difference_update
()¶ Update a set with the symmetric difference of itself and another.
-
toJson
(_mark_version=True)¶ Create and returns a data structure made up of jsonable items.
Return type: An instance of one the classes from NATIVE_JSON_DATATYPES
-
union
()¶ Return the union of sets as a new set.
(i.e. all elements that are in either set.)
-
update
()¶ Update a set with the union of itself and others.
-