def to_dict(self, *, include_keys=None, exclude_keys=None, use_default_excludes=True): """Converts the class to a dictionary. :include_keys: if not None, only the attrs given will be included. :exclude_keys: if not None, all attrs except those listed will be included, with respect to use_default_excludes. :use_default_excludes: if True, then the class-level exclude_keys_serialize will be combined with exclude_keys if given, or used in place of exlcude_keys if not given. """ data = self.__dict__ if include_keys: return pick(data, include_keys, transform=self._other_to_dict) else: skeys = self.exclude_keys_serialize if use_default_excludes else None ekeys = exclude_keys return exclude( data, lambda k: (skeys is not None and k in skeys) or (ekeys is not None and k in ekeys), transform=self._other_to_dict)
def test_exclude(self): d = dict(a=1, b=2, c=3, d=4) self.assertEqual(h.exclude(d, ["a", "b"]), dict(c=3, d=4)) self.assertEqual(h.exclude(d, lambda k: k >= "c"), dict(a=1, b=2)) self.assertEqual(h.exclude(d, ["a", "b"], transform=lambda n: n * 2), dict(c=6, d=8))