• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/python3 -i
2#
3# Copyright (c) 2019 Collabora, Ltd.
4#
5# SPDX-License-Identifier: Apache-2.0
6#
7# Author(s):    Ryan Pavlik <ryan.pavlik@collabora.com>
8"""Provides general-purpose data structures."""
9
10
11class DictOfStringSets:
12    """A dictionary where the values are sets of strings.
13
14    Has some convenience functions to allow easier maintenance via
15    the .add method."""
16
17    def __init__(self, d=None):
18        self.d = {}
19        if d:
20            for k, v in d.items():
21                self.add(k, v)
22
23    def __getitem__(self, k):
24        return self.d[k]
25
26    def __contains__(self, k):
27        return k in self.d
28
29    def get(self, k, default=None):
30        return self.d.get(k, default)
31
32    def get_dict(self):
33        return self.d
34
35    def items(self):
36        """Return an iterator like dict().items()."""
37        return self.d.items()
38
39    def keys(self):
40        """Return an iterator over keys."""
41        return self.d.keys()
42
43    def values(self):
44        """Return an iterator over values."""
45        return self.d.values()
46
47    def add_key(self, k):
48        """Ensure the set for the given key exists."""
49        if k not in self.d:
50            self.d[k] = set()
51
52    def add(self, k, v):
53        self.add_key(k)
54        if isinstance(v, str):
55            v = (v, )
56        if not isinstance(v, set):
57            v = set(v)
58        self.d[k].update(v)
59