-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__init__.py
261 lines (198 loc) · 6.41 KB
/
__init__.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
import weakref
from random import random
call = lambda cbl: cbl()
def compose(*args):
#*rest, head = args
head, rest = (lambda head, *rest: (head, rest))(*reversed(args))
return lambda *args, **kwds: reduce(lambda result, itm: itm(result), rest, head(*args, **kwds))
# Give a class access to its dynamic context, e.g.
#
# class outer:
# class inner:
# class __metaclass__(type):
# __get__ = ctxual
#
# instance = outer()
# instance is instance.inner.ctx # True
#
# A subclass is generated each time the class (inner) is accessed with a unique
# dynamic context (instance). The same subclass must be returned each time the
# class is accessed with the same dynamic context, such that:
#
# instance.inner.sample = 'Sample'
#
# # If the same subclass isn't returned then this might raise an AttributeError
# instance.inner.sample # 'Sample'
#
# This is achieved with a mapping from class and dynamic context to subclass.
# To avoid leaking memory, we make weak references to class and dynamic
# context. Subclass references class and dynamic context (this is our goal) so
# if we don't also make weak reference to subclass, then it, class, and dynamic
# context won't get finalized before mapping is finalized
#
# Recycle mapping when class or dynamic context get finalized. To simplify,
# recycle mapping when subclass is finalized. Because subclass references
# class and dynamic context, this never happens later than class or dynamic
# context get finalized. Only difference is that after subclass is finalized,
# mapping is recycled vs. a broken weak reference
# http://jdbates.blogspot.com/2011/07/in-python-how-can-you-associate-one.html
cache = weakref.WeakValueDictionary()
def ctxual(ctx, instance, *_):
try:
key = weakref.ref(ctx), weakref.ref(instance)
except TypeError:
key = weakref.ref(ctx)
try:
return cache[key]
except KeyError:
result = cache[key] = type(ctx)(ctx.__name__, (ctx,), { 'ctx': instance })
return result
def each(cbl):
gnr = cbl()
gnr.next()
# gnr.send() not a descriptor,
# http://docs.python.org/reference/datamodel.html#descriptors
def result(*args, **kwds):
try:
head, = args
except ValueError:
return gnr.send(args, **kwds)
return gnr.send(head, **kwds)
result.throw = gnr.throw
return result
# Callback is called after there are no references to this final instance, or
# after this final instance is garbage collected if it's part of a collectable
# reference cycle. Callback isn't called in the following rare (hopefully)
# cases:
#
# * Exotic situations like when the program is killed by a signal not handled
# by Python, when a Python fatal internal error is detected, or when
# os._exit() is called
#
# * There's an uncollectable reference to this final instance,
# http://docs.python.org/reference/datamodel.html#object.__del__
#
# * The weak reference instance is itself part of a circular reference
#
# Maintain references to weak references or they get destroyed before final
# instances - use weak dictionary to avoid memory leak. Maintaining reference
# as final instance property fails in case final instance is part of a
# collectable reference cycle - maybe in that case weak reference property gets
# destroyed before final instance?
#
# http://jdbates.blogspot.com/2011/04/in-python-how-can-you-reliably-call.html
ref = weakref.WeakKeyDictionary()
class final:
def __init__(ctx, callback):
ref[ctx] = weakref.ref(ctx, lambda _: callback())
def cancel(ctx):
del ref[ctx]
def head(cbl):
def result(*args, **kwds):
gnr = cbl()
gnr.next()
try:
gnr.send(*args, **kwds)
except StopIteration as e:
if e.args:
try:
head, = e.args
except ValueError:
return e.args
return head
@partial(setattr, result, 'throw')
def throw(*args, **kwds):
gnr = cbl()
gnr.next()
try:
gnr.throw(*args, **kwds)
except StopIteration as e:
if e.args:
try:
head, = e.args
except ValueError:
return e.args
return head
return result
# http://jdbates.blogspot.com/2011/04/ow-ow-ow-python-why-do-you-hurt-so-hard.html
identity = lambda ctx: ctx
class oneMany:
def __init__(ctx, *args):
ctx.asdf = list(args)
def __getattr__(ctx, name):
try:
return getattr(ctx.asdf, name)
except AttributeError:
asdf, = ctx.asdf
return getattr(asdf, name)
def __getitem__(ctx, name):
try:
return ctx.asdf[name]
except TypeError:
asdf, = ctx.asdf
return asdf[name]
def __str__(ctx):
asdf, = ctx.asdf
return str(asdf)
class manyMap:
def __init__(ctx, *args, **kwds):
ctx.asdf = dict()
for key, value in args:
ctx.append(key, value)
for key, value in kwds.iteritems():
ctx.append(key, value)
def __getattr__(ctx, name):
try:
return getattr(ctx.asdf, name)
except AttributeError:
try:
return ctx.asdf[name]
except KeyError:
raise AttributeError
def __getitem__(ctx, name):
try:
return ctx.asdf[name]
except KeyError:
try:
return getattr(ctx.asdf, name)
except (AttributeError, TypeError):
raise KeyError
__iter__ = lambda ctx: ctx.asdf.iteritems()
def append(ctx, key, value):
try:
ctx.asdf[key].append(value)
except KeyError:
ctx.asdf[key] = oneMany(value)
# functools.partial() breaks descriptor,
# http://docs.python.org/reference/datamodel.html#descriptors
class partial:
__metaclass__ = type
# No **kwds because, TypeError: unhashable type: 'dict'
def __get__(ctx, instance=None, owner=None):
try:
return cache[ctx, instance, owner]
except KeyError:
result = cache[ctx, instance, owner] = partial(ctx.cbl.__get__(instance, owner), *ctx.args, **ctx.kwds)
return result
def __init__(ctx, cbl, *args, **kwds):
ctx.cbl = cbl
ctx.args = args
ctx.kwds = kwds
def __call__(ctx, *args, **kwds):
totalArgs = list(ctx.args)
totalArgs.extend(args)
totalKwds = dict(ctx.kwds)
totalKwds.update(kwds)
return ctx.cbl(*totalArgs, **totalKwds)
def randstr(length, alphabet):
# Choose symbols from alphabet, at random
symbol = random()
result = ''
for _ in range(6):
symbol *= len(alphabet)
result += alphabet[int(symbol)]
symbol -= int(symbol)
return result
@call
class wildcard:
__contains__ = lambda *args, **kwds: True