xref: /llvm-project/lldb/examples/summaries/cocoa/attrib_fromdict.py (revision 2238dcc39358353cac21df75c3c3286ab20b8f53)
1"""
2Objective-C runtime wrapper for use by LLDB Python formatters
3
4Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5See https://llvm.org/LICENSE.txt for license information.
6SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7"""
8
9
10class AttributesDictionary:
11    def __init__(self, allow_reset=True):
12        # need to do it this way to prevent endless recursion
13        self.__dict__["_dictionary"] = {}
14        self.__dict__["_allow_reset"] = allow_reset
15
16    def __getattr__(self, name):
17        if not self._check_exists(name):
18            return None
19        value = self._dictionary[name]
20        return value
21
22    def _set_impl(self, name, value):
23        self._dictionary[name] = value
24
25    def _check_exists(self, name):
26        return name in self._dictionary
27
28    def __setattr__(self, name, value):
29        if self._allow_reset:
30            self._set_impl(name, value)
31        else:
32            self.set_if_necessary(name, value)
33
34    def set_if_necessary(self, name, value):
35        if not self._check_exists(name):
36            self._set_impl(name, value)
37            return True
38        return False
39
40    def __len__(self):
41        return len(self._dictionary)
42