aboutsummaryrefslogtreecommitdiff
blob: d884d4bd9d4cd9ace3411820986001b806796204 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# Copyright 1999-2012 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2


class SlotObject:
    __slots__ = ("__weakref__",)

    def __init__(self, **kwargs):
        classes = [self.__class__]
        while classes:
            c = classes.pop()
            if c is SlotObject:
                continue
            classes.extend(c.__bases__)
            slots = getattr(c, "__slots__", None)
            if not slots:
                continue
            for myattr in slots:
                myvalue = kwargs.pop(myattr, None)
                if myvalue is None and getattr(self, myattr, None) is not None:
                    raise AssertionError(
                        "class '%s' duplicates '%s' value in __slots__ of base class '%s'"
                        % (self.__class__.__name__, myattr, c.__name__)
                    )
                try:
                    setattr(self, myattr, myvalue)
                except AttributeError:
                    # Allow a property to override a __slots__ value, but raise an
                    # error if the intended value is something other than None.
                    if not (
                        myvalue is None
                        and isinstance(getattr(type(self), myattr, None), property)
                    ):
                        raise

        if kwargs:
            raise TypeError(
                "'%s' is an invalid keyword argument for this constructor"
                % (next(iter(kwargs)),)
            )

    def copy(self):
        """
        Create a new instance and copy all attributes
        defined from __slots__ (including those from
        inherited classes).
        """
        obj = self.__class__()

        classes = [self.__class__]
        while classes:
            c = classes.pop()
            if c is SlotObject:
                continue
            classes.extend(c.__bases__)
            slots = getattr(c, "__slots__", None)
            if not slots:
                continue
            for myattr in slots:
                setattr(obj, myattr, getattr(self, myattr))

        return obj