Minor fix in query.py
[ganeti-local] / lib / objectutils.py
1 #
2 #
3
4 # Copyright (C) 2012 Google Inc.
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 # General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 # 02110-1301, USA.
20
21 """Module for object related utils."""
22
23
24 class AutoSlots(type):
25   """Meta base class for __slots__ definitions.
26
27   """
28   def __new__(mcs, name, bases, attrs):
29     """Called when a class should be created.
30
31     @param mcs: The meta class
32     @param name: Name of created class
33     @param bases: Base classes
34     @type attrs: dict
35     @param attrs: Class attributes
36
37     """
38     assert "__slots__" not in attrs, \
39       "Class '%s' defines __slots__ when it should not" % name
40
41     attrs["__slots__"] = mcs._GetSlots(attrs)
42
43     return type.__new__(mcs, name, bases, attrs)
44
45   @classmethod
46   def _GetSlots(mcs, attrs):
47     """Used to get the list of defined slots.
48
49     @param attrs: The attributes of the class
50
51     """
52     raise NotImplementedError
53
54
55 class ValidatedSlots(object):
56   """Sets and validates slots.
57
58   """
59   __slots__ = []
60
61   def __init__(self, **kwargs):
62     """Constructor for BaseOpCode.
63
64     The constructor takes only keyword arguments and will set
65     attributes on this object based on the passed arguments. As such,
66     it means that you should not pass arguments which are not in the
67     __slots__ attribute for this class.
68
69     """
70     slots = self.GetAllSlots()
71     for (key, value) in kwargs.items():
72       if key not in slots:
73         raise TypeError("Object %s doesn't support the parameter '%s'" %
74                         (self.__class__.__name__, key))
75       setattr(self, key, value)
76
77   @classmethod
78   def GetAllSlots(cls):
79     """Compute the list of all declared slots for a class.
80
81     """
82     slots = []
83     for parent in cls.__mro__:
84       slots.extend(getattr(parent, "__slots__", []))
85     return slots
86
87   def Validate(self):
88     """Validates the slots.
89
90     This method must be implemented by the child classes.
91
92     """
93     raise NotImplementedError