|
| 1 | +"""This package contains internal utilities""" |
| 2 | + |
| 3 | +# pylint: disable=too-few-public-methods |
| 4 | +from abc import ABCMeta |
| 5 | +from typing import Any |
| 6 | + |
| 7 | + |
| 8 | +class Model(metaclass=ABCMeta): |
| 9 | + """Shared methods for MaxMind model classes""" |
| 10 | + |
| 11 | + def __eq__(self, other: Any) -> bool: |
| 12 | + return isinstance(other, self.__class__) and self.to_dict() == other.to_dict() |
| 13 | + |
| 14 | + def __ne__(self, other): |
| 15 | + return not self.__eq__(other) |
| 16 | + |
| 17 | + # pylint: disable=too-many-branches |
| 18 | + def to_dict(self): |
| 19 | + """Returns a dict of the object suitable for serialization""" |
| 20 | + result = {} |
| 21 | + for key, value in self.__dict__.items(): |
| 22 | + if key.startswith("_"): |
| 23 | + continue |
| 24 | + if hasattr(value, "to_dict") and callable(value.to_dict): |
| 25 | + if d := value.to_dict(): |
| 26 | + result[key] = d |
| 27 | + elif isinstance(value, (list, tuple)): |
| 28 | + ls = [] |
| 29 | + for e in value: |
| 30 | + if hasattr(e, "to_dict") and callable(e.to_dict): |
| 31 | + if e := e.to_dict(): |
| 32 | + ls.append(e) |
| 33 | + elif e is not None: |
| 34 | + ls.append(e) |
| 35 | + if ls: |
| 36 | + result[key] = ls |
| 37 | + # We only have dicts of strings currently. Do not bother with |
| 38 | + # the general case. |
| 39 | + elif isinstance(value, dict): |
| 40 | + if value: |
| 41 | + result[key] = value |
| 42 | + elif value is not None and value is not False: |
| 43 | + result[key] = value |
| 44 | + |
| 45 | + # network and ip_address are properties for performance reasons |
| 46 | + # pylint: disable=no-member |
| 47 | + if hasattr(self, "ip_address") and self.ip_address is not None: |
| 48 | + result["ip_address"] = str(self.ip_address) |
| 49 | + if hasattr(self, "network") and self.network is not None: |
| 50 | + result["network"] = str(self.network) |
| 51 | + |
| 52 | + return result |
0 commit comments