Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 1 # Copyright 2014 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 | |
| 5 """The meta classes used by the mojo python bindings.""" | |
| 6 | |
| 7 class MojoEnumType(type): | |
| 8 """Meta class for enumerations. | |
| 9 | |
| 10 Usage: | |
| 11 class MyEnum(object): | |
| 12 __metaclass__ = MojoEnumType | |
| 13 VALUES = [ | |
| 14 ('A', 0), | |
| 15 'B', | |
| 16 ('C', 5), | |
| 17 ] | |
| 18 | |
| 19 This will define a enum with 3 values, A = 0, B = 1 and C = 5. | |
| 20 """ | |
| 21 def __new__(mcs, name, bases, dictionary): | |
| 22 class_members = { | |
| 23 '__new__': None, | |
| 24 } | |
| 25 current_enum_value = 0 | |
| 26 for value in dictionary.pop('VALUES', []): | |
| 27 if isinstance(value, str): | |
| 28 key, enum_value = value, current_enum_value | |
| 29 elif isinstance(value, tuple): | |
| 30 key, enum_value = value | |
| 31 else: | |
| 32 raise ValueError('incorrect value: %r' % value) | |
| 33 if isinstance(key, str) and isinstance(enum_value, int): | |
| 34 class_members[key], current_enum_value = enum_value, enum_value + 1 | |
|
pkl (ping after 24h if needed)
2014/09/04 18:07:20
This is going to silently overwrite previously def
qsr
2014/09/05 11:46:02
Not really, if that happens, that must be caught a
| |
| 35 else: | |
| 36 raise ValueError('incorrect value: %r' % value) | |
| 37 return type.__new__(mcs, name, bases, class_members) | |
| 38 | |
| 39 def __setattr__(mcs, key, value): | |
| 40 raise NotImplementedError | |
| OLD | NEW |