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
-
__cause__
¶ exception cause
-
__class__
¶ alias of
builtins.type
-
__context__
¶ exception context
-
__delattr__
¶ Implement delattr(self, name).
-
__dict__
= mappingproxy({'__module__': 'schrodinger.models.json', '__weakref__': <attribute '__weakref__' of 'JSONDecodeError' objects>, '__doc__': None})¶
-
__dir__
() → list¶ default dir() implementation
-
__eq__
¶ Return self==value.
-
__format__
()¶ default object formatter
-
__ge__
¶ Return self>=value.
-
__getattribute__
¶ Return getattr(self, name).
-
__gt__
¶ Return self>value.
-
__hash__
¶ Return hash(self).
-
__init__
¶ Initialize self. See help(type(self)) for accurate signature.
-
__init_subclass__
()¶ This method is called when a class is subclassed.
The default implementation does nothing. It may be overridden to extend subclasses.
-
__le__
¶ Return self<=value.
-
__lt__
¶ Return self<value.
-
__module__
= 'schrodinger.models.json'¶
-
__ne__
¶ Return self!=value.
-
__new__
()¶ Create and return a new object. See help(type) for accurate signature.
-
__reduce__
()¶ helper for pickle
-
__reduce_ex__
()¶ helper for pickle
-
__repr__
¶ Return repr(self).
-
__setattr__
¶ Implement setattr(self, name, value).
-
__setstate__
()¶
-
__sizeof__
() → int¶ size of object in memory, in bytes
-
__str__
¶ Return str(self).
-
__subclasshook__
()¶ Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).
-
__suppress_context__
¶
-
__traceback__
¶
-
__weakref__
¶ list of weak references to the object (if defined)
-
args
¶
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
-
exception
schrodinger.models.json.
JSONEncodeError
¶ Bases:
ValueError
-
__cause__
¶ exception cause
-
__class__
¶ alias of
builtins.type
-
__context__
¶ exception context
-
__delattr__
¶ Implement delattr(self, name).
-
__dict__
= mappingproxy({'__module__': 'schrodinger.models.json', '__weakref__': <attribute '__weakref__' of 'JSONEncodeError' objects>, '__doc__': None})¶
-
__dir__
() → list¶ default dir() implementation
-
__eq__
¶ Return self==value.
-
__format__
()¶ default object formatter
-
__ge__
¶ Return self>=value.
-
__getattribute__
¶ Return getattr(self, name).
-
__gt__
¶ Return self>value.
-
__hash__
¶ Return hash(self).
-
__init__
¶ Initialize self. See help(type(self)) for accurate signature.
-
__init_subclass__
()¶ This method is called when a class is subclassed.
The default implementation does nothing. It may be overridden to extend subclasses.
-
__le__
¶ Return self<=value.
-
__lt__
¶ Return self<value.
-
__module__
= 'schrodinger.models.json'¶
-
__ne__
¶ Return self!=value.
-
__new__
()¶ Create and return a new object. See help(type) for accurate signature.
-
__reduce__
()¶ helper for pickle
-
__reduce_ex__
()¶ helper for pickle
-
__repr__
¶ Return repr(self).
-
__setattr__
¶ Implement setattr(self, name, value).
-
__setstate__
()¶
-
__sizeof__
() → int¶ size of object in memory, in bytes
-
__str__
¶ Return str(self).
-
__subclasshook__
()¶ Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).
-
__suppress_context__
¶
-
__traceback__
¶
-
__weakref__
¶ list of weak references to the object (if defined)
-
args
¶
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
-
class
schrodinger.models.json.
AttributableType
¶ Bases:
list
-
__add__
¶ Return self+value.
-
__class__
¶ alias of
builtins.type
-
__contains__
¶ Return key in self.
-
__delattr__
¶ Implement delattr(self, name).
-
__delitem__
¶ Delete self[key].
-
__dict__
= mappingproxy({'__module__': 'schrodinger.models.json', '__dict__': <attribute '__dict__' of 'AttributableType' objects>, '__weakref__': <attribute '__weakref__' of 'AttributableType' objects>, '__doc__': None})¶
-
__dir__
() → list¶ default dir() implementation
-
__eq__
¶ Return self==value.
-
__format__
()¶ default object formatter
-
__ge__
¶ Return self>=value.
-
__getattribute__
¶ Return getattr(self, name).
-
__getitem__
()¶ x.__getitem__(y) <==> x[y]
-
__gt__
¶ Return self>value.
-
__hash__
= None¶
-
__iadd__
¶ Implement self+=value.
-
__imul__
¶ Implement self*=value.
-
__init__
¶ Initialize self. See help(type(self)) for accurate signature.
-
__init_subclass__
()¶ This method is called when a class is subclassed.
The default implementation does nothing. It may be overridden to extend subclasses.
-
__iter__
¶ Implement iter(self).
-
__le__
¶ Return self<=value.
-
__len__
¶ Return len(self).
-
__lt__
¶ Return self<value.
-
__module__
= 'schrodinger.models.json'¶
-
__mul__
¶ Return self*value.n
-
__ne__
¶ Return self!=value.
-
__new__
()¶ Create and return a new object. See help(type) for accurate signature.
-
__reduce__
()¶ helper for pickle
-
__reduce_ex__
()¶ helper for pickle
-
__repr__
¶ Return repr(self).
-
__reversed__
()¶ L.__reversed__() – return a reverse iterator over the list
-
__rmul__
¶ Return self*value.
-
__setattr__
¶ Implement setattr(self, name, value).
-
__setitem__
¶ Set self[key] to value.
-
__sizeof__
()¶ L.__sizeof__() – size of L in memory, in bytes
-
__str__
¶ Return str(self).
-
__subclasshook__
()¶ Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).
-
__weakref__
¶ list of weak references to the object (if defined)
-
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)
-
classmethod
__init_subclass__
()¶ This method is called when a class is subclassed.
The default implementation does nothing. It may be overridden to extend subclasses.
-
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.
-
__class__
¶ alias of
builtins.type
-
__delattr__
¶ Implement delattr(self, name).
-
__dict__
= mappingproxy({'__module__': 'schrodinger.models.json', '__doc__': "\n A mixin that aids in making a class Jsonable. Users must define\n `toJsonImplementation(self)` and `fromJsonImplementation(cls, json_dict)`. For example::\n\n class Person(JsonableClassMixin, object):\n\n def __init__(self, full_name, age):\n self.full_name = full_name\n self.age = age\n\n def toJsonImplementation(self):\n return {'full_name':self.full_name,\n 'age':self.age}\n\n @classmethod\n def fromJsonImplementation(cls, json_dict):\n return cls(json_dict['full_name'], json_dict['age'])\n\n Now `dump` and `dumps` can encode :code:`Person`::\n\n # Encode to a file\n abe = Person('Abraham Lincoln', 208)\n with open('abe.json', 'w') as out_file:\n json.dump(abe, out_file)\n\n # Encode to a string\n abe_json_string = json.dumps(abe)\n\n If you want to decode the json string or file, you'll have to use\n `loads` or `load` and then feed in the result to your class' public\n class method `fromJson()`::\n\n # Loading an object from a json file\n with open('abe.json', 'r') as in_file:\n abe_json = json.load(in_file)\n abe = Person.fromJson(abe_json)\n\n # Loading an object from a json string\n abe_json = json.loads(abe_json_string)\n abe = Person.fromJson(abe_json)\n ", '__init_subclass__': <classmethod object>, 'toJsonImplementation': <function JsonableClassMixin.toJsonImplementation>, 'fromJsonImplementation': <classmethod object>, 'toJson': <function JsonableClassMixin.toJson>, 'fromJson': <classmethod object>, '_getJsonAdapters': <classmethod object>, '_setJsonAdapters': <classmethod object>, 'get_version': <function JsonableClassMixin.get_version>, '__dict__': <attribute '__dict__' of 'JsonableClassMixin' objects>, '__weakref__': <attribute '__weakref__' of 'JsonableClassMixin' objects>})¶
-
__dir__
() → list¶ default dir() implementation
-
__eq__
¶ Return self==value.
-
__format__
()¶ default object formatter
-
__ge__
¶ Return self>=value.
-
__getattribute__
¶ Return getattr(self, name).
-
__gt__
¶ Return self>value.
-
__hash__
¶ Return hash(self).
-
__init__
¶ Initialize self. See help(type(self)) for accurate signature.
-
__le__
¶ Return self<=value.
-
__lt__
¶ Return self<value.
-
__module__
= 'schrodinger.models.json'¶
-
__ne__
¶ Return self!=value.
-
__new__
()¶ Create and return a new object. See help(type) for accurate signature.
-
__reduce__
()¶ helper for pickle
-
__reduce_ex__
()¶ helper for pickle
-
__repr__
¶ Return repr(self).
-
__setattr__
¶ Implement setattr(self, name, value).
-
__sizeof__
() → int¶ size of object in memory, in bytes
-
__str__
¶ Return str(self).
-
__subclasshook__
()¶ Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).
-
__weakref__
¶ list of weak references to the object (if defined)
-
classmethod
-
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, **kwargs)¶ A wrapper that automatically decodes json strings serialized from
JsonableClassMixin
objects.If the json string was not an encoded
JsonableClassMixin
object, this function will behave exactly like the builtinjson.loads
.
-
schrodinger.models.json.
load
(fp, **kwargs)¶ A wrapper that automatically decodes json files serialized from
JsonableClassMixin
objects.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.
-
__class__
¶ alias of
enum.EnumMeta
-
__members__
= mappingproxy(OrderedDict())¶
-
__module__
= 'schrodinger.models.json'¶
-
-
class
schrodinger.models.json.
JsonableIntEnum
(*args, **kwargs)¶ Bases:
int
,schrodinger.models.json.JsonableClassMixin
,enum.Enum
An enumeration.
-
__class__
¶ alias of
enum.EnumMeta
-
__members__
= mappingproxy(OrderedDict())¶
-
__module__
= 'schrodinger.models.json'¶
-
-
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
-
__and__
¶ Return self&value.
-
__class__
¶ alias of
builtins.type
-
__contains__
()¶ x.__contains__(y) <==> y in x.
-
__delattr__
¶ Implement delattr(self, name).
-
__dict__
= mappingproxy({'__module__': 'schrodinger.models.json', 'ENCODING_KEY': '_python_set_', 'toJsonImplementation': <function JsonableSet.toJsonImplementation>, 'fromJsonImplementation': <classmethod object>, '__dict__': <attribute '__dict__' of 'JsonableSet' objects>, '__doc__': None, '_JsonableSet_jsonAdapters': []})¶
-
__dir__
() → list¶ default dir() implementation
-
__eq__
¶ Return self==value.
-
__format__
()¶ default object formatter
-
__ge__
¶ Return self>=value.
-
__getattribute__
¶ Return getattr(self, name).
-
__gt__
¶ Return self>value.
-
__hash__
= None¶
-
__iand__
¶ Return self&=value.
-
__init__
¶ Initialize self. See help(type(self)) for accurate signature.
-
classmethod
__init_subclass__
()¶ This method is called when a class is subclassed.
The default implementation does nothing. It may be overridden to extend subclasses.
-
__ior__
¶ Return self|=value.
-
__isub__
¶ Return self-=value.
-
__iter__
¶ Implement iter(self).
-
__ixor__
¶ Return self^=value.
-
__le__
¶ Return self<=value.
-
__len__
¶ Return len(self).
-
__lt__
¶ Return self<value.
-
__module__
= 'schrodinger.models.json'¶
-
__ne__
¶ Return self!=value.
-
__new__
()¶ Create and return a new object. See help(type) for accurate signature.
-
__or__
¶ Return self|value.
-
__rand__
¶ Return value&self.
-
__reduce__
()¶ Return state information for pickling.
-
__reduce_ex__
()¶ helper for pickle
-
__repr__
¶ Return repr(self).
-
__ror__
¶ Return value|self.
-
__rsub__
¶ Return value-self.
-
__rxor__
¶ Return value^self.
-
__setattr__
¶ Implement setattr(self, name, value).
-
__sizeof__
() → size of S in memory, in bytes¶
-
__str__
¶ Return str(self).
-
__sub__
¶ Return self-value.
-
__subclasshook__
()¶ Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).
-
__weakref__
¶ list of weak references to the object (if defined)
-
__xor__
¶ Return self^value.
-
add
()¶ Add an element to a set.
This has no effect if the element is already present.
-
clear
()¶ Remove all elements from this set.
-
copy
()¶ Return a shallow copy of a 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.
-