• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2017 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5class SlotsMetaclass(type):
6  """This metaclass requires all subclasses to define __slots__.
7
8  Usage:
9    class Foo(object):
10      __metaclass__ = slots_metaclass.SlotsMetaclass
11      __slots__ = '_property0', '_property1',
12
13  __slots__ must be a tuple containing string names of all properties that the
14  class contains.
15  Defining __slots__ reduces memory usage, accelerates property access, and
16  prevents dynamically adding unlisted properties.
17  If you need to dynamically add unlisted properties to a class with this
18  metaclass, then take a step back and rethink your goals. If you really really
19  need to dynamically add unlisted properties to a class with this metaclass,
20  add '__dict__' to its __slots__.
21  """
22
23  def __new__(mcs, name, bases, attrs):
24    assert '__slots__' in attrs, 'Class "%s" must define __slots__' % name
25    assert isinstance(attrs['__slots__'], tuple), '__slots__ must be a tuple'
26
27    return super(SlotsMetaclass, mcs).__new__(mcs, name, bases, attrs)
28