Completed
Push — master ( 82760b...c05ef7 )
by Lambda
02:32
created

Context.from_dict()   B

Complexity

Conditions 3

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
dl 0
loc 27
rs 8.8571
c 0
b 0
f 0
1
"""Context module."""
2
3
4
class Context:
5
    """Context class which used to store/restore data.
6
7
    Note:
8
        This class defines ``__slots__`` attribute so sub-class must override
9
        the attribute to extend available attributes.
10
11
    Attributes:
12
        nvim (Nvim): The ``neovim.Nvim`` instance.
13
        text (str): A user input text of the prompt.
14
        caret_locus (int): A locus index of the caret in the prompt.
15
16
    """
17
18
    __slots__ = ('text', 'caret_locus')
19
20
    def __init__(self) -> None:
21
        """Constructor.
22
23
        Args:
24
            nvim (Nvim): The ``neovim.Nvim`` instance.
25
26
        """
27
        self.text = ''
28
        self.caret_locus = 0
29
30
    def to_dict(self) -> dict:
31
        """Convert a context instance into a dictionary.
32
33
        Use ``Context.from_dict(d)`` to restore a context instance from a
34
        dictionary.
35
36
        Example:
37
            >>> context = Context()
38
            >>> context.text = 'Hello'
39
            >>> context.caret_locus = 3
40
            >>> d = context.to_dict()
41
            >>> d['text']
42
            'Hello'
43
            >>> d['caret_locus']
44
            3
45
46
        Returns:
47
            dict: A context dictionary.
48
49
        """
50
        return {
51
            k: getattr(self, k)
52
            for k in self.__slots__
53
        }
54
55
    @classmethod
56
    def from_dict(cls, d: dict) -> 'Context':
57
        """Create a new context instance from a dictionary.
58
59
        Use ``context.to_dict()`` to create a corresponding dictionary.
60
61
        Args:
62
            d (dict): A corresponding dictionary.
63
64
        Example:
65
            >>> context = Context.from_dict({
66
            ...     'text': 'Hello',
67
            ...     'caret_locus': 3,
68
            ... })
69
            >>> context.text
70
            'Hello'
71
            >>> context.caret_locus
72
            3
73
74
        Returns:
75
            Context: A context instance.
76
        """
77
        context = cls.__new__(cls)
78
        for k, v in d.items():
79
            if k in cls.__slots__:
80
                setattr(context, k, v)
81
        return context
82