Completed
Pull Request — master (#179)
by Björn
22:44
created

neovim.api.RemoteSequence.__contains__()   A

Complexity

Conditions 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1
Metric Value
cc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
"""Code shared between the API classes."""
2
import functools
3
4 6
5
class Remote(object):
6
7
    """Base class for Nvim objects(buffer/window/tabpage).
8
9
    Each type of object has it's own specialized class with API wrappers around
10
    the msgpack-rpc session. This implements equality which takes the remote
11
    object handle into consideration.
12
    """
13 6
    def __init__(self, session, code_data):
14
        """Initialize from session and code_data immutable object.
15 6
16
        The `code_data` contains serialization information required for
17
        msgpack-rpc calls. It must be immutable for Buffer equality to work.
18 6
        """
19
        self._session = session
20 6
        self.code_data = code_data
21
        self.api = RemoteApi(self, self._api_prefix)
0 ignored issues
show
Bug introduced by
The Instance of Remote does not seem to have a member named _api_prefix.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
22
        self.vars = RemoteMap(self, self._api_prefix + 'get_var',
0 ignored issues
show
Bug introduced by
The Instance of Remote does not seem to have a member named _api_prefix.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
23 6
                              self._api_prefix + 'set_var')
0 ignored issues
show
Bug introduced by
The Instance of Remote does not seem to have a member named _api_prefix.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
24
        self.options = RemoteMap(self, self._api_prefix + 'get_option',
0 ignored issues
show
Bug introduced by
The Instance of Remote does not seem to have a member named _api_prefix.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
25
                                 self._api_prefix + 'set_option')
0 ignored issues
show
Bug introduced by
The Instance of Remote does not seem to have a member named _api_prefix.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
26
27
    def __eq__(self, other):
28
        """Return True if `self` and `other` are the same object."""
29
        return (hasattr(other, 'code_data') and
30
                other.code_data == self.code_data)
31
32
    def __hash__(self):
33
        """Return hash based on remote object id."""
34 6
        return self.code_data.__hash__()
35
36 6
    def request(self, name, *args, **kwargs):
37 6
        """Wrapper for nvim.request."""
38 6
        return self._session.request(name, self, *args, **kwargs)
39 6
40
41 6
class RemoteApi(object):
42
    def __init__(self, obj, api_prefix):
43 6
        self._obj = obj
44
        self._api_prefix = api_prefix
45 6
46
    def __getattr__(self, name):
47 6
        return functools.partial(self._obj.request, self._api_prefix + name)
48
49 6
50
class RemoteMap(object):
51 6
52
    """Represents a string->object map stored in Nvim.
53 6
54 6
    This is the dict counterpart to the `RemoteSequence` class, but it is used
55
    as a generic way of retrieving values from the various map-like data
56
    structures present in Nvim.
57 6
58
    It is used to provide a dict-like API to vim variables and options.
59 6
    """
60
61
    def __init__(self, obj, get_method, set_method=None, self_obj=None):
0 ignored issues
show
Unused Code introduced by
The argument self_obj seems to be unused.
Loading history...
62
        """Initialize a RemoteMap with session, getter/setter and self_obj."""
63
64
        self._get = functools.partial(obj.request, get_method)
65 6
        self._set = None
66
        if set_method:
67
            self._set = functools.partial(obj.request, set_method)
68
69
    def __getitem__(self, key):
70
        """Return a map value by key."""
71
        return self._get(key)
72
73 6
    def __setitem__(self, key, value):
74
        """Set a map value by key(if the setter was provided)."""
75
        if not self._set:
76
            raise TypeError('This dict is read-only')
77
        self._set(key, value)
78
79
    def __delitem__(self, key):
80
        """Delete a map value by associating None with the key."""
81
        if not self._set:
82
            raise TypeError('This dict is read-only')
83
        return self._set(key, None)
84
85
    def __contains__(self, key):
86
        """Check if key is present in the map."""
87
        try:
88
            self._get(key)
89
            return True
90
        except Exception:
0 ignored issues
show
Best Practice introduced by
Catching very general exceptions such as Exception is usually not recommended.

Generally, you would want to handle very specific errors in the exception handler. This ensure that you do not hide other types of errors which should be fixed.

So, unless you specifically plan to handle any error, consider adding a more specific exception.

Loading history...
91
            return False
92
93
    def get(self, key, default=None):
94 6
        """Return value for key if present, else a default value."""
95
        try:
96 6
            return self._get(key)
97
        except Exception:
0 ignored issues
show
Best Practice introduced by
Catching very general exceptions such as Exception is usually not recommended.

Generally, you would want to handle very specific errors in the exception handler. This ensure that you do not hide other types of errors which should be fixed.

So, unless you specifically plan to handle any error, consider adding a more specific exception.

Loading history...
98 6
            return default
99
100 6
101
class RemoteSequence(object):
102 6
103
    """Represents a sequence of objects stored in Nvim.
104 6
105 6
    This class is used to wrap msgapck-rpc functions that work on Nvim
106
    sequences(of lines, buffers, windows and tabpages) with an API that
107
    is similar to the one provided by the python-vim interface.
108 6
109
    For example, the 'buffers' property of the `Nvim class is a RemoteSequence
110 6
    sequence instance, and the expression `nvim.buffers[0]` is translated to
111 6
    session.request('vim_get_buffers')[0].
112 6
113
    It can also receive an optional self_obj that will be passed as first
114 6
    argument of the request. For example, `tabpage.windows[0]` is translated
115
    to: session.request('tabpage_get_windows', tabpage_instance)[0].
116 6
117
    One important detail about this class is that all methods will fetch the
118
    sequence into a list and perform the necessary manipulation
119 6
    locally(iteration, indexing, counting, etc).
120
    """
121
122
    def __init__(self, session, method):
123 6
        """Initialize a RemoteSequence with session, method and self_obj."""
124
        self._fetch = functools.partial(session.request, method)
125
126
    def __len__(self):
127
        """Return the length of the remote sequence."""
128
        return len(self._fetch())
129
130
    def __getitem__(self, idx):
131
        """Return a sequence item by index."""
132
        if not isinstance(idx, slice):
133
            return self._fetch()[idx]
134
        return self._fetch()[idx.start:idx.stop]
135
136
    def __iter__(self):
137
        """Return an iterator for the sequence."""
138
        items = self._fetch()
139
        for item in items:
140
            yield item
141
142 6
    def __contains__(self, item):
143
        """Check if an item is present in the sequence."""
144 6
        return item in self._fetch()
145 6
146
147 6
def _identity(obj, session, method, kind):
0 ignored issues
show
Unused Code introduced by
The argument method seems to be unused.
Loading history...
Unused Code introduced by
The argument kind seems to be unused.
Loading history...
Unused Code introduced by
The argument session seems to be unused.
Loading history...
148
    return obj
149
150
151
class DecodeHook(object):
152
153 3
    """SessionHook subclass that decodes utf-8 strings coming from Nvim.
154 3
155 3
    This class is useful for python3, where strings are now unicode by
156 3
    default(byte strings need to be prefixed with "b").
157
    """
158 3
159
    def __init__(self, encoding='utf-8', encoding_errors='strict'):
160 3
        """Initialize with encoding and encoding errors policy."""
161
        self.encoding = encoding
162
        self.encoding_errors = encoding_errors
163
164 6
    def decode_if_bytes(self, obj):
165
        if isinstance(obj, bytes):
166
            return obj.decode(self.encoding, errors=self.encoding_errors)
167
        return obj
168
169
    def walk(self, obj):
170
        """Decode bytes found in obj (any msgpack object).
171
172 6
        Uses encoding and policy specified in constructor.
173
        """
174 3
        return walk(self.decode_if_bytes, obj)
175 3
176 3
177
def walk(fn, obj, *args):
178 6
    """Recursively walk an object graph applying `fn`/`args` to objects."""
179 3
    if type(obj) in [list, tuple]:
180 3
        return list(walk(fn, o, *args) for o in obj)
181 3
    if type(obj) is dict:
182
        return dict((walk(fn, k, *args), walk(fn, v, *args)) for k, v in
183 6
                    obj.items())
184
    return fn(obj, *args)
185