forked from simos/keyboardlayouteditor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Enum.py
60 lines (51 loc) · 2.52 KB
/
Enum.py
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
#!/usr/bin/env python
# -*- encoding: UTF-8 -*-
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
class Enum:
"""Create an enumerated type, then add var/value pairs to it.
The constructor and the method .ints(names) take a list of variable names,
and assign them consecutive integers as values. The method .strs(names)
assigns each variable name to itself (that is variable 'v' has value 'v').
The method .vals(a=99, b=200) allows you to assign any value to variables.
A 'list of variable names' can also be a string, which will be .split().
The method .end() returns one more than the maximum int value.
Example: opcodes = Enum("add sub load store").vals(illegal=255)."""
def __init__(self, names=[]): self.ints(names)
def set(self, var, val):
"""Set var to the value val in the enum."""
if var in vars(self).keys(): raise AttributeError("duplicate var in enum")
if val in vars(self).values(): raise ValueError("duplicate value in enum")
vars(self)[var] = val
return self
def strs(self, names):
"""Set each of the names to itself (as a string) in the enum."""
for var in self._parse(names): self.set(var, var)
return self
def ints(self, names):
"""Set each of the names to the next highest int in the enum."""
for var in self._parse(names): self.set(var, self.end())
return self
def vals(self, **entries):
"""Set each of var=val pairs in the enum."""
for (var, val) in entries.items(): self.set(var, val)
return self
def end(self):
"""One more than the largest int value in the enum, or 0 if none."""
try: return max([x for x in vars(self).values() if type(x)==type(0)]) + 1
except ValueError: return 0
def _parse(self, names):
### If names is a string, parse it as a list of names.
if type(names) == type(""): return names.split()
else: return names