forked from fluentpython/example-code-2e
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnanoenum.py
41 lines (33 loc) · 880 Bytes
/
nanoenum.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
# This is a simplification of an idea by João S. O. Bueno (@gwidion)
# shared privately with me, with permission to use in Fluent Python 2e.
"""
Testing ``KeyIsValueDict``::
>>> adict = KeyIsValueDict()
>>> len(adict)
0
>>> adict['first']
'first'
>>> adict
{'first': 'first'}
>>> adict['second']
'second'
>>> len(adict)
2
>>> adict
{'first': 'first', 'second': 'second'}
>>> adict['__magic__']
Traceback (most recent call last):
...
KeyError: '__magic__'
"""
class KeyIsValueDict(dict):
def __missing__(self, key):
if key.startswith('__') and key.endswith('__'):
raise KeyError(key)
self[key] = key
return key
class NanoEnumMeta(type):
def __prepare__(name, bases, **kwargs):
return KeyIsValueDict()
class NanoEnum(metaclass=NanoEnumMeta):
pass