-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.py
108 lines (81 loc) · 2.92 KB
/
core.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import inspect
import collections
class AttrDict(dict):
__setattr__ = dict.__setitem__
def __getattr__(self, attr):
# Take care that getattr() raises AttributeError, not KeyError.
# Required e.g. for hasattr(), deepcopy and OrderedDict.
try:
return dict.__getitem__(self, attr)
except KeyError:
raise AttributeError("Attribute %r not found" % attr)
def rename(self, old, new):
self[new] = self.pop(old)
def get(self, key, default=None):
if key not in self:
return default
return self.__getitem__(key)
def __getstate__(self): return self
def __setstate__(self, d): self = d
@property
def safe(self):
"""
A property that can be used to safely access the dictionary.
When a key is not found, the access getter will return None.
To be used as:
AttrDict().safe.keypoint == None
"""
return DictAccess(self)
class AttrDefaultDict(collections.defaultdict):
__setattr__ = collections.defaultdict.__setitem__
def __getattr__(self, attr):
# Take care that getattr() raises AttributeError, not KeyError.
# Required e.g. for hasattr(), deepcopy and OrderedDict.
try:
return collections.defaultdict.__getitem__(self, attr)
except KeyError:
raise AttributeError("Attribute %r not found" % attr)
def rename(self, old, new):
self[new] = self.pop(old)
def get(self, key, default=None):
if key not in self:
return default
return self.__getitem__(key)
def __getstate__(self):
return self
def __setstate__(self, d):
self = d
@property
def safe(self):
"""
A property that can be used to safely access the dictionary.
When a key is not found, the access getter will return None.
To be used as:
AttrDict().safe.keypoint == None
"""
return DictAccess(self)
class DictAccess():
# A simple access class that returns None if a key is not found
def __init__(self, parent):
super().__setattr__('parent', parent)
def __getattr__(self, item):
try:
return dict.__getitem__(self.parent, item)
except KeyError:
return None
class optional:
""" A function decorator that returns the first argument to the function if yes=False
I chose a class-based decorator since I find the syntax less confusing. """
def __init__(self, n=0):
""" Decorator parameters """
self.n = n
def __call__(self, func):
""" Wrapping """
def wrapper(*args, yes=True, **kwargs):
if yes:
return func(*args, **kwargs)
n = self.n
if inspect.ismethod(func):
n += 1
return args[n]
return wrapper