-
Notifications
You must be signed in to change notification settings - Fork 242
/
utils.py
610 lines (522 loc) · 20.3 KB
/
utils.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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
#coding: cp1251
from __future__ import absolute_import, print_function
from pony.py23compat import PY2, imap, basestring, unicode, pickle, iteritems
import io, re, os, os.path, sys, datetime, inspect, types, linecache, warnings, json
from itertools import count as _count
from inspect import isfunction, ismethod
from time import strptime
from os import urandom
from codecs import BOM_UTF8, BOM_LE, BOM_BE
from locale import getpreferredencoding
from bisect import bisect
from collections import defaultdict
from functools import update_wrapper, wraps
from xml.etree import cElementTree
from copy import deepcopy
import pony
from pony import options
from pony.thirdparty.compiler import ast
from pony.thirdparty.decorator import decorator as _decorator
if pony.MODE.startswith('GAE-'): localbase = object
else: from threading import local as localbase
class PonyDeprecationWarning(DeprecationWarning):
pass
def deprecated(stacklevel, message):
warnings.warn(message, PonyDeprecationWarning, stacklevel)
warnings.simplefilter('once', PonyDeprecationWarning)
def _improved_decorator(caller, func):
if isfunction(func):
return _decorator(caller, func)
def pony_wrapper(*args, **kwargs):
return caller(func, *args, **kwargs)
return pony_wrapper
def decorator(caller, func=None):
if func is not None:
return _improved_decorator(caller, func)
def new_decorator(func):
return _improved_decorator(caller, func)
if isfunction(caller):
update_wrapper(new_decorator, caller)
return new_decorator
##def simple_decorator(dec):
## def new_dec(func):
## def pony_wrapper(*args, **kwargs):
## return dec(func, *args, **kwargs)
## return copy_func_attrs(pony_wrapper, func, dec.__name__)
## return copy_func_attrs(new_dec, dec, 'simple_decorator')
##@simple_decorator
##def decorator_with_params(dec, *args, **kwargs):
## if len(args) == 1 and not kwargs:
## func = args[0]
## new_func = dec(func)
## return copy_func_attrs(new_func, func, dec.__name__)
## def parameterized_decorator(old_func):
## new_func = dec(func, *args, **kwargs)
## return copy_func_attrs(new_func, func, dec.__name__)
## return parameterized_decorator
def decorator_with_params(dec):
def parameterized_decorator(*args, **kwargs):
if len(args) == 1 and isfunction(args[0]) and not kwargs:
return decorator(dec(), args[0])
return decorator(dec(*args, **kwargs))
return parameterized_decorator
@decorator
def cut_traceback(func, *args, **kwargs):
if not options.CUT_TRACEBACK:
return func(*args, **kwargs)
try: return func(*args, **kwargs)
except AssertionError: raise
except Exception:
exc_type, exc, tb = sys.exc_info()
full_tb = tb
last_pony_tb = None
try:
while tb.tb_next:
module_name = tb.tb_frame.f_globals['__name__']
if module_name == 'pony' or (module_name is not None # may be None during import
and module_name.startswith('pony.')):
last_pony_tb = tb
tb = tb.tb_next
if last_pony_tb is None: raise
module_name = tb.tb_frame.f_globals.get('__name__') or ''
if module_name.startswith('pony.utils') and tb.tb_frame.f_code.co_name == 'throw':
reraise(exc_type, exc, last_pony_tb)
reraise(exc_type, exc, full_tb)
finally:
del exc, full_tb, tb, last_pony_tb
cut_traceback_depth = 2
if pony.MODE != 'INTERACTIVE':
cut_traceback_depth = 0
def cut_traceback(func):
return func
if PY2:
exec('''def reraise(exc_type, exc, tb):
try: raise exc_type, exc, tb
finally: del tb''')
else:
def reraise(exc_type, exc, tb):
try: raise exc.with_traceback(tb)
finally: del exc, tb
def throw(exc_type, *args, **kwargs):
if isinstance(exc_type, Exception):
assert not args and not kwargs
exc = exc_type
else: exc = exc_type(*args, **kwargs)
exc.__cause__ = None
try:
if not (pony.MODE == 'INTERACTIVE' and options.CUT_TRACEBACK):
raise exc
else:
raise exc # Set "pony.options.CUT_TRACEBACK = False" to see full traceback
finally: del exc
def truncate_repr(s, max_len=100):
s = repr(s)
return s if len(s) <= max_len else s[:max_len-3] + '...'
codeobjects = {}
def get_codeobject_id(codeobject):
codeobject_id = id(codeobject)
if codeobject_id not in codeobjects:
codeobjects[codeobject_id] = codeobject
return codeobject_id
lambda_args_cache = {}
def get_lambda_args(func):
if type(func) is types.FunctionType:
codeobject = func.func_code if PY2 else func.__code__
cache_key = get_codeobject_id(codeobject)
elif isinstance(func, ast.Lambda):
cache_key = func
else: assert False # pragma: no cover
names = lambda_args_cache.get(cache_key)
if names is not None: return names
if type(func) is types.FunctionType:
if hasattr(inspect, 'signature'):
names, argsname, kwname, defaults = [], None, None, []
for p in inspect.signature(func).parameters.values():
if p.default is not p.empty:
defaults.append(p.default)
if p.kind == p.POSITIONAL_OR_KEYWORD:
names.append(p.name)
elif p.kind == p.VAR_POSITIONAL:
argsname = p.name
elif p.kind == p.VAR_KEYWORD:
kwname = p.name
elif p.kind == p.POSITIONAL_ONLY:
throw(TypeError, 'Positional-only arguments like %s are not supported' % p.name)
elif p.kind == p.KEYWORD_ONLY:
throw(TypeError, 'Keyword-only arguments like %s are not supported' % p.name)
else: assert False
else:
names, argsname, kwname, defaults = inspect.getargspec(func)
elif isinstance(func, ast.Lambda):
names = func.argnames
if func.kwargs: names, kwname = names[:-1], names[-1]
else: kwname = None
if func.varargs: names, argsname = names[:-1], names[-1]
else: argsname = None
defaults = func.defaults
else: assert False # pragma: no cover
if argsname: throw(TypeError, '*%s is not supported' % argsname)
if kwname: throw(TypeError, '**%s is not supported' % kwname)
if defaults: throw(TypeError, 'Defaults are not supported')
lambda_args_cache[cache_key] = names
return names
_cache = {}
MAX_CACHE_SIZE = 1000
@decorator
def cached(f, *args, **kwargs):
key = (f, args, tuple(sorted(kwargs.items())))
value = _cache.get(key)
if value is not None: return value
if len(_cache) == MAX_CACHE_SIZE: _cache.clear()
return _cache.setdefault(key, f(*args, **kwargs))
def error_method(*args, **kwargs):
raise TypeError()
_ident_re = re.compile(r'^[A-Za-z_]\w*\Z')
# is_ident = ident_re.match
def is_ident(string):
'is_ident(string) -> bool'
return bool(_ident_re.match(string))
_name_parts_re = re.compile(r'''
[A-Z][A-Z0-9]+(?![a-z]) # ACRONYM
| [A-Z][a-z]* # Capitalized or single capital
| [a-z]+ # all-lowercase
| [0-9]+ # numbers
| _+ # underscores
''', re.VERBOSE)
def split_name(name):
"split_name('Some_FUNNYName') -> ['Some', 'FUNNY', 'Name']"
if not _ident_re.match(name):
raise ValueError('Name is not correct Python identifier')
list = _name_parts_re.findall(name)
if not (list[0].strip('_') and list[-1].strip('_')):
raise ValueError('Name must not starting or ending with underscores')
return [ s for s in list if s.strip('_') ]
def uppercase_name(name):
"uppercase_name('Some_FUNNYName') -> 'SOME_FUNNY_NAME'"
return '_'.join(s.upper() for s in split_name(name))
def lowercase_name(name):
"uppercase_name('Some_FUNNYName') -> 'some_funny_name'"
return '_'.join(s.lower() for s in split_name(name))
def camelcase_name(name):
"uppercase_name('Some_FUNNYName') -> 'SomeFunnyName'"
return ''.join(s.capitalize() for s in split_name(name))
def mixedcase_name(name):
"mixedcase_name('Some_FUNNYName') -> 'someFunnyName'"
list = split_name(name)
return list[0].lower() + ''.join(s.capitalize() for s in list[1:])
def import_module(name):
"import_module('a.b.c') -> <module a.b.c>"
mod = sys.modules.get(name)
if mod is not None: return mod
mod = __import__(name)
components = name.split('.')
for comp in components[1:]: mod = getattr(mod, comp)
return mod
if sys.platform == 'win32':
_absolute_re = re.compile(r'^(?:[A-Za-z]:)?[\\/]')
else: _absolute_re = re.compile(r'^/')
def is_absolute_path(filename):
return bool(_absolute_re.match(filename))
def absolutize_path(filename, frame_depth):
if is_absolute_path(filename): return filename
code_filename = sys._getframe(frame_depth+1).f_code.co_filename
if not is_absolute_path(code_filename):
if code_filename.startswith('<') and code_filename.endswith('>'):
if pony.MODE == 'INTERACTIVE': raise ValueError(
'When in interactive mode, please provide absolute file path. Got: %r' % filename)
raise EnvironmentError('Unexpected module filename, which is not absolute file path: %r' % code_filename)
code_path = os.path.dirname(code_filename)
return os.path.join(code_path, filename)
def shortened_filename(filename):
if pony.MAIN_DIR is None: return filename
maindir = pony.MAIN_DIR + os.sep
if filename.startswith(maindir): return filename[len(maindir):]
return filename
def get_mtime(filename):
stat = os.stat(filename)
mtime = stat.st_mtime
if sys.platform == "win32": mtime -= stat.st_ctime
return mtime
coding_re = re.compile(r'coding[:=]\s*([-\w.]+)')
def detect_source_encoding(filename):
for i, line in enumerate(linecache.getlines(filename)):
if i == 0 and line.startswith(BOM_UTF8): return 'utf-8'
if not line.lstrip().startswith('#'): continue
match = coding_re.search(line)
if match is not None: return match.group(1)
else: return options.SOURCE_ENCODING or getpreferredencoding()
escape_re = re.compile(r'''
(?<!\\)\\ # single backslash
(?:
x[0-9a-f]{2} # byte escaping
| u[0-9a-f]{4} # unicode escaping
| U[0-9a-f]{8} # long unicode escaping
)
''', re.VERBOSE)
def restore_escapes(s, console_encoding=None, source_encoding=None):
if not options.RESTORE_ESCAPES: return s
if source_encoding is None:
source_encoding = options.SOURCE_ENCODING or getpreferredencoding()
if console_encoding is None:
try: console_encoding = getattr(sys.stderr, 'encoding', None)
except: console_encoding = None # workaround for PythonWin win32ui.error "The MFC object has died."
console_encoding = console_encoding or options.CONSOLE_ENCODING
console_encoding = console_encoding or getpreferredencoding()
try: s = s.decode(source_encoding).encode(console_encoding)
except (UnicodeDecodeError, UnicodeEncodeError): pass
def f(match):
esc = match.group()
code = int(esc[2:], 16)
if esc.startswith('\\x'):
if code < 32: return esc
try: return chr(code).decode(source_encoding).encode(console_encoding)
except (UnicodeDecodeError, UnicodeEncodeError): return esc
char = unichr(code)
try: return char.encode(console_encoding)
except UnicodeEncodeError: return esc
return escape_re.sub(f, s)
def current_timestamp():
return datetime2timestamp(datetime.datetime.now())
def datetime2timestamp(d):
result = d.isoformat(' ')
if len(result) == 19: return result + '.000000'
return result
def timestamp2datetime(t):
time_tuple = strptime(t[:19], '%Y-%m-%d %H:%M:%S')
microseconds = int((t[20:26] + '000000')[:6])
return datetime.datetime(*(time_tuple[:6] + (microseconds,)))
def read_text_file(fname, encoding=None):
text = file(fname).read()
for bom, enc in [ (BOM_UTF8, 'utf8'), (BOM_LE, 'utf-16le'), (BOM_BE, 'utf-16be') ]:
if text[:len(bom)] == bom: return text[len(bom):].decode(enc)
try: return text.decode('utf8')
except UnicodeDecodeError:
try: return text.decode(encoding or getpreferredencoding())
except UnicodeDecodeError:
return text.decode('ascii', 'replace')
def compress(s):
zipped = s.encode('zip')
if len(zipped) < len(s): return 'Z' + zipped
return 'N' + s
def decompress(s):
first = s[0]
if first == 'N': return s[1:]
elif first == 'Z': return s[1:].decode('zip')
raise ValueError('Incorrect data')
class JsonString(unicode): pass
def json_result(obj, **kwargs):
result = JsonString(json.dumps(obj, **kwargs))
result.media_type = 'application/json'
if 'encoding' in kwargs: result.charset = kwargs['encoding']
return result
expr1_re = re.compile(r'''
([A-Za-z_]\w*) # identifier (group 1)
| ([(]) # open parenthesis (group 2)
''', re.VERBOSE)
expr2_re = re.compile(r'''
\s*(?:
(;) # semicolon (group 1)
| (\.\s*[A-Za-z_]\w*) # dot + identifier (group 2)
| ([([]) # open parenthesis or braces (group 3)
)
''', re.VERBOSE)
expr3_re = re.compile(r"""
[()[\]] # parenthesis or braces (group 1)
| '''(?:[^\\]|\\.)*?''' # '''triple-quoted string'''
| \"""(?:[^\\]|\\.)*?\""" # \"""triple-quoted string\"""
| '(?:[^'\\]|\\.)*?' # 'string'
| "(?:[^"\\]|\\.)*?" # "string"
""", re.VERBOSE)
def parse_expr(s, pos=0):
z = 0
match = expr1_re.match(s, pos)
if match is None: raise ValueError()
start = pos
i = match.lastindex
if i == 1: pos = match.end() # identifier
elif i == 2: z = 2 # "("
else: assert False # pragma: no cover
while True:
match = expr2_re.match(s, pos)
if match is None: return s[start:pos], z==1
pos = match.end()
i = match.lastindex
if i == 1: return s[start:pos], False # ";" - explicit end of expression
elif i == 2: z = 2 # .identifier
elif i == 3: # "(" or "["
pos = match.end()
counter = 1
open = match.group(i)
if open == '(': close = ')'
elif open == '[': close = ']'; z = 2
else: assert False # pragma: no cover
while True:
match = expr3_re.search(s, pos)
if match is None: raise ValueError()
pos = match.end()
x = match.group()
if x == open: counter += 1
elif x == close:
counter -= 1
if not counter: z += 1; break
else: assert False # pragma: no cover
def tostring(x):
if isinstance(x, basestring): return x
if hasattr(x, '__unicode__'):
try: return unicode(x)
except: pass
if hasattr(x, 'makeelement'): return cElementTree.tostring(x)
try: return str(x)
except: pass
try: return repr(x)
except: pass
if type(x) == types.InstanceType: return '<%s instance at 0x%X>' % (x.__class__.__name__)
return '<%s object at 0x%X>' % (x.__class__.__name__)
def strjoin(sep, strings, source_encoding='ascii', dest_encoding=None):
"Can join mix of unicode and byte strings in different encodings"
strings = list(strings)
try: return sep.join(strings)
except UnicodeDecodeError: pass
for i, s in enumerate(strings):
if isinstance(s, str):
strings[i] = s.decode(source_encoding, 'replace').replace(u'\ufffd', '?')
result = sep.join(strings)
if dest_encoding is None: return result
return result.encode(dest_encoding, 'replace')
def make_offsets(s):
offsets = [ 0 ]
si = -1
try:
while True:
si = s.index('\n', si + 1)
offsets.append(si + 1)
except ValueError: pass
offsets.append(len(s))
return offsets
def pos2lineno(pos, offsets):
line = bisect(offsets, pos, 0, len(offsets)-1)
if line == 1: offset = pos
else: offset = pos - offsets[line - 1]
return line, offset
def getline(text, offsets, lineno):
return text[offsets[lineno-1]:offsets[lineno]]
def getlines(text, offsets, lineno, context=1):
if context <= 0: return [], None
start = max(0, lineno - 1 - context//2)
end = min(len(offsets)-1, start + context)
start = max(0, end - context)
lines = []
for i in range(start, end): lines.append(text[offsets[i]:offsets[i+1]])
index = lineno - 1 - start
return lines, index
def getlines2(filename, lineno, context=1):
if context <= 0: return [], None
lines = linecache.getlines(filename)
if not lines: return [], None
start = max(0, lineno - 1 - context//2)
end = min(len(lines), start + context)
start = max(0, end - context)
lines = lines[start:start+context]
index = lineno - 1 - start
return lines, index
def count(*args, **kwargs):
if kwargs: return _count(*args, **kwargs)
if len(args) != 1: return _count(*args)
arg = args[0]
if hasattr(arg, 'count'): return arg.count()
try: it = iter(arg)
except TypeError: return _count(arg)
return len(set(it))
def avg(iter):
count = 0
sum = 0.0
for elem in iter:
if elem is None: continue
sum += elem
count += 1
if not count: return None
return sum / count
def group_concat(items, sep=','):
if items is None:
return None
return str(sep).join(str(item) for item in items)
def coalesce(*args):
for arg in args:
if arg is not None:
return arg
return None
def distinct(iter):
d = defaultdict(int)
for item in iter:
d[item] = d[item] + 1
return d
def concat(*args):
return ''.join(tostring(arg) for arg in args)
def between(x, a, b):
return a <= x <= b
def is_utf8(encoding):
return encoding.upper().replace('_', '').replace('-', '') in ('UTF8', 'UTF', 'U8')
def _persistent_id(obj):
if obj is Ellipsis:
return "Ellipsis"
def _persistent_load(persid):
if persid == "Ellipsis":
return Ellipsis
raise pickle.UnpicklingError("unsupported persistent object")
def pickle_ast(val):
pickled = io.BytesIO()
pickler = pickle.Pickler(pickled)
pickler.persistent_id = _persistent_id
pickler.dump(val)
return pickled
def unpickle_ast(pickled):
pickled.seek(0)
unpickler = pickle.Unpickler(pickled)
unpickler.persistent_load = _persistent_load
return unpickler.load()
def copy_ast(tree):
return unpickle_ast(pickle_ast(tree))
def _hashable_wrap(func):
@wraps(func, assigned=('__name__', '__doc__'))
def new_func(self, *args, **kwargs):
if getattr(self, '_hash', None) is not None:
assert False, 'Cannot mutate HashableDict instance after the hash value is calculated'
return func(self, *args, **kwargs)
return new_func
class HashableDict(dict):
def __hash__(self):
result = getattr(self, '_hash', None)
if result is None:
result = 0
for key, value in self.items():
result ^= hash(key)
result ^= hash(value)
self._hash = result
return result
def __deepcopy__(self, memo):
if getattr(self, '_hash', None) is not None:
return self
return HashableDict({deepcopy(key, memo): deepcopy(value, memo)
for key, value in iteritems(self)})
__setitem__ = _hashable_wrap(dict.__setitem__)
__delitem__ = _hashable_wrap(dict.__delitem__)
clear = _hashable_wrap(dict.clear)
pop = _hashable_wrap(dict.pop)
popitem = _hashable_wrap(dict.popitem)
setdefault = _hashable_wrap(dict.setdefault)
update = _hashable_wrap(dict.update)
def deref_proxy(value):
t = type(value)
if t.__name__ == 'LocalProxy' and '_get_current_object' in t.__dict__:
# Flask local proxy
value = value._get_current_object()
elif t.__name__ == 'EntityProxy':
# Pony proxy
value = value._get_object()
return value
def deduplicate(value, deduplication_cache):
t = type(value)
try:
return deduplication_cache[t].setdefault(value, value)
except:
return value