4 # Copyright (C) 2012 Google Inc.
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.
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.
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
21 """Module for object related utils."""
24 class AutoSlots(type):
25 """Meta base class for __slots__ definitions.
28 def __new__(mcs, name, bases, attrs):
29 """Called when a class should be created.
31 @param mcs: The meta class
32 @param name: Name of created class
33 @param bases: Base classes
35 @param attrs: Class attributes
38 assert "__slots__" not in attrs, \
39 "Class '%s' defines __slots__ when it should not" % name
41 attrs["__slots__"] = mcs._GetSlots(attrs)
43 return type.__new__(mcs, name, bases, attrs)
46 def _GetSlots(mcs, attrs):
47 """Used to get the list of defined slots.
49 @param attrs: The attributes of the class
52 raise NotImplementedError
55 class ValidatedSlots(object):
56 """Sets and validates slots.
61 def __init__(self, **kwargs):
62 """Constructor for BaseOpCode.
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.
70 slots = self.GetAllSlots()
71 for (key, value) in kwargs.items():
73 raise TypeError("Object %s doesn't support the parameter '%s'" %
74 (self.__class__.__name__, key))
75 setattr(self, key, value)
79 """Compute the list of all declared slots for a class.
83 for parent in cls.__mro__:
84 slots.extend(getattr(parent, "__slots__", []))
88 """Validates the slots.
90 This method must be implemented by the child classes.
93 raise NotImplementedError