Completed
Push — master ( a55149...0becad )
by Oleksandr
02:02
created

il2fb.commons.BaseStructure.to_primitive()   A

Complexity

Conditions 3

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3
Metric Value
cc 3
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 3
rs 9.4286
1
# -*- coding: utf-8 -*-
2
3
4 1
class BaseStructure(object):
5 1
    __slots__ = []
6
7 1
    def __eq__(self, other):
8 1
        if not isinstance(other, self.__class__):
9 1
            return NotImplemented
10
11 1
        return all([
12
            getattr(self, x) == getattr(other, x)
13
            for x in self.__slots__
14
        ])
15
16 1
    def __ne__(self, other):
17 1
        return not (self == other)
18
19 1
    def __hash__(self):
20 1
        return hash(tuple(
21
            getattr(self, x) for x in self.__slots__
22
        ))
23
24 1
    def to_primitive(self, context=None):
25 1
        fields = ((key, getattr(self, key)) for key in self.__slots__)
26 1
        return {
27
            key: self._to_primitive(value, context)
28
            for key, value in fields
29
        }
30
31 1
    @staticmethod
32
    def _to_primitive(instance, context):
33 1
        if hasattr(instance, 'to_primitive'):
34 1
            return instance.to_primitive(context)
35 1
        elif hasattr(instance, 'isoformat'):
36 1
            return instance.isoformat()
37
        else:
38
            return instance
39