#!/usr/bin/env python# -*- coding: utf-8 -*-## This file is part of the `pypath` python module## Copyright 2014-2023# EMBL, EMBL-EBI, Uniklinik RWTH Aachen, Heidelberg University## Authors: see the file `README.rst`# Contact: Dénes Türei (turei.denes@gmail.com)## Distributed under the GPLv3 License.# See accompanying file LICENSE.txt or copy at# https://www.gnu.org/licenses/gpl-3.0.html## Website: https://pypath.omnipathdb.org/#fromfuture.utilsimportiteritemsimportjsonimportitertoolsimportpypath.share.commonascommon
[docs]classAttributeHandler(object):""" Base class for other classes which carry custom attributes (data) in a dedicated dict under the `attrs` attribute. """__slots__=['attrs',]
[docs]defupdate_attrs(self,attrs=None,**kwargs):""" Updates the attributes stored here. The attributes with identical keys are merged using the :py:func:`pypath.share.common.combine_attrs` function. The new attributes can be provided three ways: an object with an attribute called `attrs`; a dictionary of attributes; or the attributes as keyword arguments. """ifhasattr(attrs,'attrs'):attrs=attrs.attrsself._update_attrs(attrs,**kwargs)
[docs]defserialize(self,**kwargs):""" Generates a JSON string with the full contents of the attributes, without any whitespace or line break. Returns (str): The attributes JSON serialized. """returnself._serialize(self.attrs,**kwargs)
@classmethoddef_serialize(cls,attrs,top_key_prefix=False,prefix_sep='_',**kwargs):ifnotattrs:return''param={'indent':None,'separators':(',',':'),}param.update(kwargs)default=param.pop('default',lambdax:x)param['default']=(lambdax:# sets are not serializable by the json module# hence we always convert them to listslist(x)ifisinstance(x,set)else# additional defaults included heredefault)iftop_key_prefix:attrs=dict(itemfortop_key,valiniteritems(attrs)foritemincls._add_prefix(val,top_key,sep=prefix_sep))returnjson.dumps(attrs,**param)@staticmethoddef_add_prefix(d,prefix,sep='_'):d=difisinstance(d,dict)elsed.attrsforkey,valiniteritems(d):yield('%s%s%s'%(prefix,sep,key),val)def__str__(self):returnself.serialize()def__len__(self):returnlen(self.attrs)def__contains__(self,other):returnotherinself.attrsdef__getitem__(self,other):returnself.attrs[other]ifotherinself.attrselseNone