-
Notifications
You must be signed in to change notification settings - Fork 5
/
odictliteral.py
42 lines (35 loc) · 1.11 KB
/
odictliteral.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
try:
from collections import OrderedDict
except:
from ordereddict import OrderedDict
try:
from reprlib import recursive_repr
except:
# don't cope with recursive repr calls in py2
def recursive_repr(fillvalue='...'): return (lambda f: f)
try:
from collections.abc import Iterable
except:
Iterable = tuple
__all__ = ["odict"]
__version__ = '1.0.0'
class odictType(type):
syntax_error = SyntaxError("Allowed syntax: odict[<k>: <v>(, <k>: <v>...)]")
def __getitem__(self, keys):
if isinstance(keys, slice):
keys = (keys,)
if not isinstance(keys, Iterable):
raise self.syntax_error
od = self()
for k in keys:
if not isinstance(k, slice) or k.step is not None:
raise self.syntax_error
od[k.start] = k.stop
return od
@recursive_repr(fillvalue="odict[...]")
def odict_repr(self):
if len(self) == 0:
return "odict()"
else:
return "odict[%s]" % (", ".join("%r: %r" % (k,v) for k,v in self.items()),)
odict = odictType(str('odict'), (OrderedDict,), {"__repr__": odict_repr})