Datasets:

Modalities:
Tabular
Text
Formats:
json
ArXiv:
DOI:
Libraries:
Datasets
Dask
License:
Dataset Viewer
Auto-converted to Parquet
id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
0
0101/pipetools
0101_pipetools/pipetools/main.py
pipetools.main.XObject
class XObject(object): def __init__(self, func=None): self._func = func set_name(lambda: get_name(func) if func else 'X', self) def __repr__(self): return get_name(self) def __invert__(self): return self._func or set_name('X', lambda x: x) def bind(self, name, func): set_name(name, func) return XObject((self._func | func) if self._func else (pipe | func)) def __call__(self, *args, **kwargs): name = lambda: 'X(%s)' % repr_args(*args, **kwargs) return self.bind(name, lambda x: x(*args, **kwargs)) def __hash__(self): return super(XObject, self).__hash__() def __eq__(self, other): return self.bind(lambda: 'X == {0!r}'.format(other), lambda x: x == other) def __getattr__(self, name): return self.bind(lambda: 'X.{0}'.format(name), lambda x: getattr(x, name)) def __getitem__(self, item): return self.bind(lambda: 'X[{0!r}]'.format(item), lambda x: x[item]) def __gt__(self, other): return self.bind(lambda: 'X > {0!r}'.format(other), lambda x: x > other) def __ge__(self, other): return self.bind(lambda: 'X >= {0!r}'.format(other), lambda x: x >= other) def __lt__(self, other): return self.bind(lambda: 'X < {0!r}'.format(other), lambda x: x < other) def __le__(self, other): return self.bind(lambda: 'X <= {0!r}'.format(other), lambda x: x <= other) def __ne__(self, other): return self.bind(lambda: 'X != {0!r}'.format(other), lambda x: x != other) def __pos__(self): return self.bind(lambda: '+X', lambda x: +x) def __neg__(self): return self.bind(lambda: '-X', lambda x: -x) def __mul__(self, other): return self.bind(lambda: 'X * {0!r}'.format(other), lambda x: x * other) def __rmul__(self, other): return self.bind(lambda: '{0!r} * X'.format(other), lambda x: other * x) def __matmul__(self, other): # prevent syntax error on legacy interpretors from operator import matmul return self.bind(lambda: 'X @ {0!r}'.format(other), lambda x: matmul(x, other)) def __rmatmul__(self, other): from operator import matmul return self.bind(lambda: '{0!r} @ X'.format(other), lambda x: matmul(other, x)) def __div__(self, other): return self.bind(lambda: 'X / {0!r}'.format(other), lambda x: x / other) def __rdiv__(self, other): return self.bind(lambda: '{0!r} / X'.format(other), lambda x: other / x) def __truediv__(self, other): return self.bind(lambda: 'X / {0!r}'.format(other), lambda x: x / other) def __rtruediv__(self, other): return self.bind(lambda: '{0!r} / X'.format(other), lambda x: other / x) def __floordiv__(self, other): return self.bind(lambda: 'X // {0!r}'.format(other), lambda x: x // other) def __rfloordiv__(self, other): return self.bind(lambda: '{0!r} // X'.format(other), lambda x: other // x) def __mod__(self, other): return self.bind(lambda: 'X % {0!r}'.format(other), lambda x: x % other) def __rmod__(self, other): return self.bind(lambda: '{0!r} % X'.format(other), lambda x: other % x) def __add__(self, other): return self.bind(lambda: 'X + {0!r}'.format(other), lambda x: x + other) def __radd__(self, other): return self.bind(lambda: '{0!r} + X'.format(other), lambda x: other + x) def __sub__(self, other): return self.bind(lambda: 'X - {0!r}'.format(other), lambda x: x - other) def __rsub__(self, other): return self.bind(lambda: '{0!r} - X'.format(other), lambda x: other - x) def __pow__(self, other): return self.bind(lambda: 'X ** {0!r}'.format(other), lambda x: x ** other) def __rpow__(self, other): return self.bind(lambda: '{0!r} ** X'.format(other), lambda x: other ** x) def __lshift__(self, other): return self.bind(lambda: 'X << {0!r}'.format(other), lambda x: x << other) def __rlshift__(self, other): return self.bind(lambda: '{0!r} << X'.format(other), lambda x: other << x) def __rshift__(self, other): return self.bind(lambda: 'X >> {0!r}'.format(other), lambda x: x >> other) def __rrshift__(self, other): return self.bind(lambda: '{0!r} >> X'.format(other), lambda x: other >> x) def __and__(self, other): return self.bind(lambda: 'X & {0!r}'.format(other), lambda x: x & other) def __rand__(self, other): return self.bind(lambda: '{0!r} & X'.format(other), lambda x: other & x) def __xor__(self, other): return self.bind(lambda: 'X ^ {0!r}'.format(other), lambda x: x ^ other) def __rxor__(self, other): return self.bind(lambda: '{0!r} ^ X'.format(other), lambda x: other ^ x) def __ror__(self, func): return pipe | func | self def __or__(self, func): if isinstance(func, Pipe): return func.__ror__(self) return pipe | self | func def _in_(self, y): return self.bind(lambda: 'X._in_({0!r})'.format(y), lambda x: x in y)
class XObject(object): def __init__(self, func=None): pass def __repr__(self): pass def __invert__(self): pass def bind(self, name, func): pass def __call__(self, *args, **kwargs): pass def __hash__(self): pass def __eq__(self, other): pass def __getattr__(self, name): pass def __getitem__(self, item): pass def __gt__(self, other): pass def __ge__(self, other): pass def __lt__(self, other): pass def __le__(self, other): pass def __ne__(self, other): pass def __pos__(self): pass def __neg__(self): pass def __mul__(self, other): pass def __rmul__(self, other): pass def __matmul__(self, other): pass def __rmatmul__(self, other): pass def __div__(self, other): pass def __rdiv__(self, other): pass def __truediv__(self, other): pass def __rtruediv__(self, other): pass def __floordiv__(self, other): pass def __rfloordiv__(self, other): pass def __mod__(self, other): pass def __rmod__(self, other): pass def __add__(self, other): pass def __radd__(self, other): pass def __sub__(self, other): pass def __rsub__(self, other): pass def __pow__(self, other): pass def __rpow__(self, other): pass def __lshift__(self, other): pass def __rlshift__(self, other): pass def __rshift__(self, other): pass def __rrshift__(self, other): pass def __and__(self, other): pass def __rand__(self, other): pass def __xor__(self, other): pass def __rxor__(self, other): pass def __ror__(self, func): pass def __or__(self, func): pass def _in_(self, y): pass
46
0
2
0
2
0
1
0.01
1
2
1
0
45
1
45
45
144
45
98
50
50
1
98
50
50
2
1
1
47
1
0101/pipetools
0101_pipetools/pipetools/main.py
pipetools.main.Pipe
class Pipe(object): """ Pipe-style combinator. Example:: p = pipe | F | G | H p(x) == H(G(F(x))) """ def __init__(self, func=None): self.func = func self.__name__ = 'Pipe' def __str__(self): return get_name(self.func) __repr__ = __str__ @staticmethod def compose(first, second): name = lambda: '{0} | {1}'.format(get_name(first), get_name(second)) def composite(*args, **kwargs): return second(first(*args, **kwargs)) return set_name(name, composite) @classmethod def bind(cls, first, second, new_cls=None): return (new_cls or cls)( first if second is None else second if first is None else cls.compose(first, second)) def __or__(self, next_func): # Handle multiple pipes in pipe definition and also changing pipe type to e.g. Maybe # this is needed because of evaluation order pipe_in_a_pipe = isinstance(next_func, Pipe) and next_func.func is None new_cls = type(next_func) if pipe_in_a_pipe else None next = None if pipe_in_a_pipe else prepare_function_for_pipe(next_func) return self.bind(self.func, next, new_cls) def __ror__(self, prev_func): return self.bind(prepare_function_for_pipe(prev_func), self.func) def __lt__(self, thing): return self.func(thing) if self.func else thing def __call__(self, *args, **kwargs): return self.func(*args, **kwargs) def __get__(self, instance, owner): return partial(self, instance) if instance else self
class Pipe(object): ''' Pipe-style combinator. Example:: p = pipe | F | G | H p(x) == H(G(F(x))) ''' def __init__(self, func=None): pass def __str__(self): pass @staticmethod def compose(first, second): pass def composite(*args, **kwargs): pass @classmethod def bind(cls, first, second, new_cls=None): pass def __or__(self, next_func): pass def __ror__(self, prev_func): pass def __lt__(self, thing): pass def __call__(self, *args, **kwargs): pass def __get__(self, instance, owner): pass
13
1
3
0
3
0
2
0.25
1
2
0
1
7
2
9
9
54
14
32
19
19
8
27
17
16
3
1
0
16
2
0101/pipetools
0101_pipetools/test_pipetools/test_utils.py
test_pipetools.test_utils.TestTakeFirst
class TestTakeFirst: def test_take_first(self): assert [0, 1, 2] == list(take_first(3)(range(10)))
class TestTakeFirst: def test_take_first(self): pass
2
0
2
0
2
0
1
0
0
2
0
0
1
0
1
1
4
1
3
2
1
0
3
2
1
1
0
0
1
3
0101/pipetools
0101_pipetools/setup.py
setup.PyTest
class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): # import here, cause outside the eggs aren't loaded import pytest error_code = pytest.main(self.test_args) sys.exit(error_code)
class PyTest(TestCommand): def finalize_options(self): pass def run_tests(self): pass
3
0
5
0
4
1
1
0.11
1
0
0
0
2
2
2
2
12
2
9
7
5
1
9
7
5
1
1
0
2
4
0101/pipetools
0101_pipetools/test_pipetools/test_decorators.py
test_pipetools.test_decorators.TestPipeUtilsRepr
class TestPipeUtilsRepr: def test_basic(self): f = foreach(my_func) assert repr(f) == 'foreach(my_func)' def test_partially_applied(self): f = foreach(my_func, 42, kwarg=2) assert repr(f) == 'foreach(my_func, 42, kwarg=2)' def test_string_formatting(self): f = foreach("{0} asdf {1} jk;l") assert repr(f) == "foreach('{0} asdf {1} jk;l')" def test_ds_builder(self): f = sort_by([X.attr, X * 2]) assert repr(f) == 'sort_by([X.attr, X * 2])' def test_repr_doesnt_get_called_when_not_necessary(self): class Something(object): def __repr__(self): assert False, "__repr__ called when not necessary" foreach(Something()) unless(Exception, Something())
class TestPipeUtilsRepr: def test_basic(self): pass def test_partially_applied(self): pass def test_string_formatting(self): pass def test_ds_builder(self): pass def test_repr_doesnt_get_called_when_not_necessary(self): pass class Something(object): def __repr__(self): pass
8
0
4
1
3
0
1
0
0
2
1
0
5
0
5
5
27
8
19
12
11
0
19
12
11
1
0
0
6
5
0101/pipetools
0101_pipetools/test_pipetools/test_main.py
test_pipetools.test_main.Bunch
class Bunch: def __init__(self, **kwargs): self.__dict__.update(kwargs)
class Bunch: def __init__(self, **kwargs): pass
2
0
2
0
2
0
1
0
0
0
0
0
1
0
1
1
3
0
3
2
1
0
3
2
1
1
0
0
1
6
0101/pipetools
0101_pipetools/test_pipetools/test_main.py
test_pipetools.test_main.TestMaybe
class TestMaybe(TestPipe): # maybe should also pass default pipe tests pipe = property(lambda self: maybe) def test_maybe_basic(self): f = maybe | (lambda: None) | X * 2 assert f() is None def test_none_input(self): assert (None > maybe | sum) is None def test_none_input_call(self): assert (maybe | sum)(None) is None
class TestMaybe(TestPipe): def test_maybe_basic(self): pass def test_none_input(self): pass def test_none_input_call(self): pass
4
0
3
0
2
0
1
0.11
1
0
0
0
3
0
3
10
15
5
9
6
5
1
9
6
5
1
2
0
3
7
0101/pipetools
0101_pipetools/test_pipetools/test_utils.py
test_pipetools.test_utils.TestTakeUntil
class TestTakeUntil: def test_basic(self): f = take_until(X > 5) assert list(f([1, 2, 3, 1, 6, 1, 3])) == [1, 2, 3, 1] def test_including(self): f = take_until(X > 5).including assert ([1, 2, 3, 1, 6, 1, 3] > f | list) == [1, 2, 3, 1, 6] def test_including_all(self): f = take_until(X > 50).including assert ([1, 2, 3, 1, 6, 1, 3] > f | list) == [1, 2, 3, 1, 6, 1, 3]
class TestTakeUntil: def test_basic(self): pass def test_including(self): pass def test_including_all(self): pass
4
0
3
0
3
0
1
0
0
1
0
0
3
0
3
3
13
3
10
7
6
0
10
7
6
1
0
0
3
8
0101/pipetools
0101_pipetools/test_pipetools/test_utils.py
test_pipetools.test_utils.TestTee
class TestTee: def test_tee(self): store = [] result = "input" > X | tee(X | reversed | "".join | store.append) | X[2:] assert store == ["tupni"] assert result == "put"
class TestTee: def test_tee(self): pass
2
0
7
2
5
0
1
0
0
1
0
0
1
0
1
1
9
3
6
4
4
0
6
4
4
1
0
0
1
9
0101/pipetools
0101_pipetools/test_pipetools/test_utils.py
test_pipetools.test_utils.TestSortBy
class TestSortBy: def test_x(self): result = sort_by(-X[1])(zip('what', [1, 2, 3, 4])) assert result == [ ('t', 4), ('a', 3), ('h', 2), ('w', 1), ] def test_descending(self): result = zip('what', [1, 2, 3, 4]) > sort_by(X[1]).descending assert result == [ ('t', 4), ('a', 3), ('h', 2), ('w', 1), ]
class TestSortBy: def test_x(self): pass def test_descending(self): pass
3
0
10
2
8
0
1
0
0
1
0
0
2
0
2
2
23
6
17
5
14
0
7
5
4
1
0
0
2
10
0101/pipetools
0101_pipetools/test_pipetools/test_utils.py
test_pipetools.test_utils.TestSelectFirst
class TestSelectFirst: def test_select_first(self): result = select_first(X % 2 == 0)([3, 4, 5, 6]) assert result == 4 def test_select_first_none(self): result = select_first(X == 2)([0, 1, 0, 1]) assert result is None def test_select_first_empty(self): assert select_first(X)([]) is None
class TestSelectFirst: def test_select_first(self): pass def test_select_first_none(self): pass def test_select_first_empty(self): pass
4
0
3
0
3
0
1
0
0
0
0
0
3
0
3
3
12
3
9
6
5
0
9
6
5
1
0
0
3
11
0101/pipetools
0101_pipetools/test_pipetools/test_utils.py
test_pipetools.test_utils.TestRegexCondidion
class TestRegexCondidion: def test_where_regex(self): data = [ 'foo bar', 'boo far', 'foolproof', ] assert (data > where(r'^foo') | list) == [ 'foo bar', 'foolproof', ] def test_select_first_regex(self): data = [ 'foo bar', 'boo far', 'foolproof', ] assert (data > select_first(r'^b.*r$')) == 'boo far' def test_none_doesnt_match(self): data = [ 'foo bar', 'boo far', None, 'foolproof', ] assert (data > where(r'^foo') | list) == [ 'foo bar', 'foolproof', ]
class TestRegexCondidion: def test_where_regex(self): pass def test_select_first_regex(self): pass def test_none_doesnt_match(self): pass
4
0
9
0
9
0
1
0
0
1
0
0
3
0
3
3
32
3
29
7
25
0
10
7
6
1
0
0
3
12
0101/pipetools
0101_pipetools/test_pipetools/test_utils.py
test_pipetools.test_utils.TestPipeUtil
class TestPipeUtil: def test_pipability(self): f = range | foreach(X) | sum result = f(4) assert result == 6 def test_input(self): result = range(5) > where(X % 2) | list assert result == [1, 3]
class TestPipeUtil: def test_pipability(self): pass def test_input(self): pass
3
0
4
1
4
0
1
0
0
2
0
0
2
0
2
2
11
3
8
6
5
0
8
6
5
1
0
0
2
13
0101/pipetools
0101_pipetools/test_pipetools/test_utils.py
test_pipetools.test_utils.TestListMaker
class TestListMaker: def test_make_list(self): result = [1, 2, 3] > foreach([X, X % 2]) | list assert result == [[1, 1], [2, 0], [3, 1]]
class TestListMaker: def test_make_list(self): pass
2
0
3
0
3
0
1
0
0
1
0
0
1
0
1
1
5
1
4
3
2
0
4
3
2
1
0
0
1
14
0101/pipetools
0101_pipetools/test_pipetools/test_utils.py
test_pipetools.test_utils.TestGroupBy
class TestGroupBy: def test_basic(self): src = [1, 2, 3, 4, 5, 6] assert (src > group_by(X % 2) | dict) == {0: [2, 4, 6], 1: [1, 3, 5]}
class TestGroupBy: def test_basic(self): pass
2
0
3
0
3
0
1
0
0
1
0
0
1
0
1
1
5
1
4
3
2
0
4
3
2
1
0
0
1
15
0101/pipetools
0101_pipetools/test_pipetools/test_utils.py
test_pipetools.test_utils.TestFlatten
class TestFlatten: def test_flatten(self): assert (list(flatten([1, [2, 3], (4, ('five', 6))])) == [1, 2, 3, 4, 'five', 6]) def test_flatten_args(self): assert (list(flatten(1, [2, 3], (4, ('five', 6)))) == [1, 2, 3, 4, 'five', 6]) def test_flatten_dict(self): assert (list(flatten([[{'a': 1}], {'b': 2}, 'c'], {'d': 3})) == [{'a': 1}, {'b': 2}, 'c', {'d': 3}])
class TestFlatten: def test_flatten(self): pass def test_flatten_args(self): pass def test_flatten_dict(self): pass
4
0
3
0
3
0
1
0
0
1
0
0
3
0
3
3
13
3
10
4
6
0
7
4
3
1
0
0
3
16
0101/pipetools
0101_pipetools/test_pipetools/test_main.py
test_pipetools.test_main.TestPipe
class TestPipe(object): pipe = property(lambda self: pipe) def test_pipe(self): p = self.pipe | str | (lambda x: x * 2) assert p(5) == '55' def test_pipe_right(self): f = sum | self.pipe | str assert f([1, 2, 3]) == '6' def test_pipe_input(self): result = [1, 2, 3] > self.pipe | sum assert result == 6 def test_pipe_right_X(self): f = X[0] | self.pipe | str assert f([1, 2, 3]) == '1' def test_string_formatting(self): f = self.pipe | 'The answer is {0}.' assert f(42) == 'The answer is 42.' def test_unicode_formatting(self): f = self.pipe | u'That will be ยฃ {0}, please.' assert f(42) == u'That will be ยฃ 42, please.' def test_makes_a_bound_method(self): class SomeClass(object): attr = 'foo bar' method = X.attr.split() | reversed | ' '.join assert SomeClass().method() == 'bar foo'
class TestPipe(object): def test_pipe(self): pass def test_pipe_right(self): pass def test_pipe_input(self): pass def test_pipe_right_X(self): pass def test_string_formatting(self): pass def test_unicode_formatting(self): pass def test_makes_a_bound_method(self): pass class SomeClass(object):
9
0
4
1
3
0
1
0
1
2
1
1
7
0
7
7
41
16
25
18
16
0
25
18
16
1
1
0
7
17
0101/pipetools
0101_pipetools/test_pipetools/test_main.py
test_pipetools.test_main.TestPipeInAPipe
class TestPipeInAPipe: def test_maybe_in_a_pipe_catches_none(self): f = pipe | str | int | (lambda x: None) | maybe | X.hello assert f(3) is None def test_maybe_in_a_pipe_goes_through(self): f = pipe | str | int | maybe | (X * 2) assert f(3) == 6 def test_maybe_in_a_pipe_not_active_before_its_place(self): f = pipe | str | (lambda x: None) | int | maybe | X.hello with pytest.raises(TypeError): f(3) def test_pipe_in_a_pipe_because_why_not(self): f = pipe | str | pipe | int assert f(3) == 3
class TestPipeInAPipe: def test_maybe_in_a_pipe_catches_none(self): pass def test_maybe_in_a_pipe_goes_through(self): pass def test_maybe_in_a_pipe_not_active_before_its_place(self): pass def test_pipe_in_a_pipe_because_why_not(self): pass
5
0
3
0
3
0
1
0
0
3
0
0
4
0
4
4
18
4
14
9
9
0
14
9
9
1
0
1
4
18
0101/pipetools
0101_pipetools/test_pipetools/test_main.py
test_pipetools.test_main.TestStringFormatter
class TestStringFormatter: def test_format_tuple(self): f = StringFormatter('{0} + {0} = {1}') assert f((1, 2)) == '1 + 1 = 2' def test_format_list(self): f = StringFormatter('{0} + {0} = {1}') assert f([1, 2]) == '1 + 1 = 2' def test_format_generator(self): f = StringFormatter('{0} + {0} = {1}') assert f(range(1, 3)) == '1 + 1 = 2' def test_format_dict(self): f = StringFormatter('{a} and {b}') assert f(dict(a='A', b='B')) == 'A and B' def test_format_one_arg(self): f = StringFormatter('This is {0}!!1') assert f('Spartah') == 'This is Spartah!!1' def test_unicode(self): f = StringFormatter('Asdf {0}') assert f(u'ลฝluลฅouฤkรฝ kลฏลˆ') == u'Asdf ลฝluลฅouฤkรฝ kลฏลˆ' def test_unicode2(self): f = StringFormatter(u'Asdf {0}') assert f(u'ลฝluลฅouฤkรฝ kลฏลˆ') == u'Asdf ลฝluลฅouฤkรฝ kลฏลˆ'
class TestStringFormatter: def test_format_tuple(self): pass def test_format_list(self): pass def test_format_generator(self): pass def test_format_dict(self): pass def test_format_one_arg(self): pass def test_unicode(self): pass def test_unicode2(self): pass
8
0
3
0
3
0
1
0
0
2
0
0
7
0
7
7
29
7
22
15
14
0
22
15
14
1
0
0
7
19
0101/pipetools
0101_pipetools/test_pipetools/test_main.py
test_pipetools.test_main.TestX
class TestX: def test_basic(self): f = ~X.startswith('Hello') assert f('Hello world') assert not f('Goodbye world') def test_chained(self): f = ~X.get('item', '').startswith('Hello') assert f({'item': 'Hello world'}) assert not f({'item': 'Goodbye world'}) assert not f({}) def test_passthrough(self): f = ~X assert f(42) == 42 def test_mod(self): f = ~(X % 2) g = ~(9 % X) assert f(3) assert not g(3) assert g(2) assert not f(2) def test_gt(self): f = ~(X > 5) g = ~(6 > X) assert f(6) assert not g(6) assert g(5) assert not f(5) def test_gte(self): f = ~(X >= 5) g = ~(4 >= X) assert f(5) assert not g(5) assert g(4) assert not f(4) def test_lt(self): f = ~(X < 5) g = ~(4 < X) assert f(4) assert not g(4) assert g(5) assert not f(5) def test_lte(self): f = ~(X <= 5) g = ~(6 <= X) assert f(5) assert not g(5) assert g(6) assert not f(6) def test_chained_gt(self): f = ~(X.thing > 5) assert f(Bunch(thing=6)) assert not f(Bunch(thing=4)) def test_index(self): f = ~(X['item']) assert f({'item': 42}) == 42 def test_eq(self): f = ~(X == 42) assert f(42) assert not f('whatever') def test_neq(self): f = ~(X != 42) assert not f(42) assert f('whatever') def test_pos(self): f = ~+X assert f(4) == 4 def test_neg(self): f = ~-X assert f(5) == -5 def test_pipe_right(self): f = str | X[0] assert f(10) == '1' def test_pipe_left(self): f = X[0] | int assert f('10') == 1 def test_call(self): f = ~X(42) assert f(lambda n: n / 2) == 21 def test_mul(self): f = ~(X * 3) g = ~(3 * X) assert f(10) == g(10) == 30 assert f('x') == g('x') == 'xxx' def test_add(self): assert (~(X + 2))(40) == 42 assert (~('4' + X))('2') == '42' assert (~([4] + X))([2]) == [4, 2] def test_sub(self): assert (~(X - 3))(5) == (5 - 3) assert (~(5 - X))(3) == (5 - 3) def test_pow(self): assert (~(X ** 3))(5) == (5 ** 3) assert (~(5 ** X))(3) == (5 ** 3) def test_div(self): assert (~(X / 2))(4) == 2 assert (~(4 / X))(2) == 2 def test_floor_dev(self): assert (~(X // 2))(5) == 2 assert (~(5 // X))(2) == 2 def test_mod(self): assert (~(X % 5))('%.2f') == '5.00' assert (~(5 % X))(2) == 1 def test_lshift(self): assert (~(X << 2))(5) == 20 assert (~(2 << X))(5) == 64 def test_rshift(self): assert (~(X >> 1))(5) == 2 assert (~(5 >> X))(1) == 2 def test_xor(self): assert (~(X ^ 2))(3) == 1 assert (~(1 ^ X))(3) == 2 def test_and(self): assert (~(X & 2))(3) == 2 assert (~(1 & X))(3) == 1 def test_in(self): container = 'asdf' f = ~X._in_(container) assert f('a') assert not f('b') def test_repr(self): f = ~X.attr(1, 2, three='four') assert repr(f) == "X.attr | X(1, 2, three='four')" def test_repr_unicode(self): f = ~(X + u"ลฝluลฅouฤkรฝ kลฏลˆ") # in this case I'll just consider not throwing an error a success assert repr(f) def test_repr_tuple(self): f = ~(X + (1, 2)) assert repr(f) == "X + (1, 2)"
class TestX: def test_basic(self): pass def test_chained(self): pass def test_passthrough(self): pass def test_mod(self): pass def test_gt(self): pass def test_gte(self): pass def test_lt(self): pass def test_lte(self): pass def test_chained_gt(self): pass def test_index(self): pass def test_eq(self): pass def test_neq(self): pass def test_pos(self): pass def test_neg(self): pass def test_pipe_right(self): pass def test_pipe_left(self): pass def test_call(self): pass def test_mul(self): pass def test_add(self): pass def test_sub(self): pass def test_pow(self): pass def test_div(self): pass def test_floor_dev(self): pass def test_mod(self): pass def test_lshift(self): pass def test_rshift(self): pass def test_xor(self): pass def test_and(self): pass def test_index(self): pass def test_repr(self): pass def test_repr_unicode(self): pass def test_repr_tuple(self): pass
33
0
5
1
4
0
1
0.01
0
3
1
0
32
0
32
32
199
70
128
62
95
1
128
62
95
1
0
0
32
20
0101/pipetools
0101_pipetools/test_pipetools/test_utils.py
test_pipetools.test_utils.TestDropFirst
class TestDropFirst: def test_list(self): src = [1, 2, 3, 4, 5, 6] assert (src > drop_first(3) | list) == [4, 5, 6] def test_iterable(self): assert (range(10000) > drop_first(9999) | list) == [9999]
class TestDropFirst: def test_list(self): pass def test_iterable(self): pass
3
0
3
0
3
0
1
0
0
2
0
0
2
0
2
2
8
2
6
4
3
0
6
4
3
1
0
0
2
21
0101/pipetools
0101_pipetools/test_pipetools/test_utils.py
test_pipetools.test_utils.TestDictMaker
class TestDictMaker: def test_make_dict(self): result = [1, 2] > foreach({'num': X, 'str': str}) | list assert result == [{'num': 1, 'str': '1'}, {'num': 2, 'str': '2'}]
class TestDictMaker: def test_make_dict(self): pass
2
0
3
0
3
0
1
0
0
2
0
0
1
0
1
1
5
1
4
3
2
0
4
3
2
1
0
0
1
22
0101/pipetools
0101_pipetools/test_pipetools/test_utils.py
test_pipetools.test_utils.TestAutoStringFormatter
class TestAutoStringFormatter: def test_foreach_format(self): result = [1, 2] > foreach("Number {0}") | list assert result == ['Number 1', 'Number 2']
class TestAutoStringFormatter: def test_foreach_format(self): pass
2
0
3
0
3
0
1
0
0
1
0
0
1
0
1
1
5
1
4
3
2
0
4
3
2
1
0
0
1
23
0101/pipetools
0101_pipetools/test_pipetools/test_main.py
test_pipetools.test_main.TestXPartial
class TestXPartial: def test_should_behave_like_partial(self): xf = xpartial(dummy, 1, kwarg='kwarg') assert xf(2, foo='bar') == ((1, 2), {'kwarg': 'kwarg', 'foo': 'bar'}) def test_x_placeholder(self): xf = xpartial(dummy, X, 2) assert xf(1) == ((1, 2), {}) def test_x_kw_placeholder(self): xf = xpartial(dummy, kwarg=X) assert xf(1) == ((), {'kwarg': 1}) def test_x_destructuring(self): xf = xpartial(dummy, X['name'], number=X['number']) d = {'name': "Fred", 'number': 42, 'something': 'else'} assert xf(d) == (('Fred',), {'number': 42}) def test_repr(self): xf = xpartial(dummy, X, 3, something=X['something']) assert repr(X | xf) == "X | dummy(X, 3, something=X['something'])" def test_should_raise_error_when_not_given_an_argument(self): # -- when created with a placeholder xf = xpartial(dummy, something=X) with pytest.raises(ValueError): xf() def test_can_xpartial_any_callable(self): class my_callable(object): def __call__(self, x): return "hello %s" % x f = xpartial(my_callable(), (X + "!")) assert f("x") == "hello x!"
class TestXPartial: def test_should_behave_like_partial(self): pass def test_x_placeholder(self): pass def test_x_kw_placeholder(self): pass def test_x_destructuring(self): pass def test_repr(self): pass def test_should_raise_error_when_not_given_an_argument(self): pass def test_can_xpartial_any_callable(self): pass class my_callable(object): def __call__(self, x): pass
10
0
4
0
4
0
1
0.04
0
2
1
0
7
0
7
7
36
8
27
18
17
1
27
18
17
1
0
1
8
24
0101/pipetools
0101_pipetools/test_pipetools/test_utils.py
test_pipetools.test_utils.TestTupleMaker
class TestTupleMaker: def test_make_tuple(self): result = [1, 2, 3] > foreach((X, X % 2)) | list assert result == [(1, 1), (2, 0), (3, 1)]
class TestTupleMaker: def test_make_tuple(self): pass
2
0
3
0
3
0
1
0
0
1
0
0
1
0
1
1
5
1
4
3
2
0
4
3
2
1
0
0
1
25
0101/pipetools
0101_pipetools/test_pipetools/test_utils.py
test_pipetools.test_utils.TestUnless
class TestUnless: def test_ok(self): f = unless(AttributeError, foreach(X.lower())) | list assert f("ABC") == ['a', 'b', 'c'] def test_with_exception(self): f = unless(AttributeError, foreach(X.lower()) | list) assert f(['A', 'B', 37]) is None def test_with_exception_in_foreach(self): f = foreach(unless(AttributeError, X.lower())) | list assert f(['A', 'B', 37]) == ['a', 'b', None] def test_partial_ok(self): f = unless(TypeError, enumerate, start=3) | list assert f('abc') == [(3, 'a'), (4, 'b'), (5, 'c')] def test_partial_exc(self): f = unless(TypeError, enumerate, start=3) assert f(42) is None def test_X_ok(self): f = unless(TypeError, X * 'x') assert f(3) == 'xxx' def test_X_exception(self): f = unless(TypeError, X * 'x') assert f('x') is None
class TestUnless: def test_ok(self): pass def test_with_exception(self): pass def test_with_exception_in_foreach(self): pass def test_partial_ok(self): pass def test_partial_exc(self): pass def test_X_ok(self): pass def test_X_exception(self): pass
8
0
3
0
3
0
1
0
0
4
0
0
7
0
7
7
29
7
22
15
14
0
22
15
14
1
0
0
7
26
0101/pipetools
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/0101_pipetools/test_pipetools/test_decorators.py
test_pipetools.test_decorators.TestPipeUtilsRepr.test_repr_doesnt_get_called_when_not_necessary.Something
class Something(object): def __repr__(self): assert False, "__repr__ called when not necessary"
class Something(object): def __repr__(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
1
4
1
3
2
1
0
3
2
1
1
1
0
1
27
0101/pipetools
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/0101_pipetools/test_pipetools/test_main.py
test_pipetools.test_main.TestPipe.test_makes_a_bound_method.SomeClass
class SomeClass(object): attr = 'foo bar' method = X.attr.split() | reversed | ' '.join
class SomeClass(object): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
1
0
0
28
0101/pipetools
0101_pipetools/test_pipetools/test_utils.py
test_pipetools.test_utils.TestAsKwargs
class TestAsKwargs: def test_as_kwargs(self): d = {'foo': 4, 'bar': 2} assert as_kwargs(lambda **kw: kw)(d) == d
class TestAsKwargs: def test_as_kwargs(self): pass
2
0
3
0
3
0
1
0
0
0
0
0
1
0
1
1
5
1
4
3
2
0
4
3
2
1
0
0
1
29
0101/pipetools
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/0101_pipetools/test_pipetools/test_main.py
test_pipetools.test_main.TestXPartial.test_can_xpartial_any_callable.my_callable
class my_callable(object): def __call__(self, x): return "hello %s" % x
class my_callable(object): def __call__(self, x): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
1
3
0
3
2
1
0
3
2
1
1
1
0
1
30
0101/pipetools
0101_pipetools/pipetools/main.py
pipetools.main.Maybe
class Maybe(Pipe): @staticmethod def compose(first, second): name = lambda: '{0} ?| {1}'.format(get_name(first), get_name(second)) def composite(*args, **kwargs): result = first(*args, **kwargs) return None if result is None else second(result) return set_name(name, composite) def __call__(self, *args, **kwargs): if len(args) == 1 and args[0] is None and not kwargs: return None return self.func(*args, **kwargs) def __lt__(self, thing): return ( None if thing is None else self.func(thing) if self.func else thing)
class Maybe(Pipe): @staticmethod def compose(first, second): pass def composite(*args, **kwargs): pass def __call__(self, *args, **kwargs): pass def __lt__(self, thing): pass
6
0
5
0
5
0
2
0
1
0
0
0
2
0
3
12
21
4
17
8
11
0
13
7
8
3
2
1
8
31
0101/pipetools
0101_pipetools/pipetools/ds_builder.py
pipetools.ds_builder.NoBuilder
class NoBuilder(ValueError): pass
class NoBuilder(ValueError): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
11
2
0
2
1
1
0
2
1
1
0
4
0
0
32
02strich/django-auth-kerberos
02strich_django-auth-kerberos/django_auth_kerberos/backends.py
django_auth_kerberos.backends.KrbBackend
class KrbBackend(ModelBackend): """ Django Authentication backend using Kerberos for password checking. """ def authenticate(self, request, username=None, password=None, **kwargs): UserModel = get_user_model() if not self.check_password(username, password): return None UserModel = get_user_model() if getattr(settings, "KRB5_CREATE_USER", True): if getattr(settings, "KRB5_USERNAME_MATCH_IEXACT", True): user, created = UserModel.objects.get_or_create(**{ UserModel.USERNAME_FIELD+"__iexact": username, "defaults": { UserModel.USERNAME_FIELD: username } }) return user else: user, created = UserModel.objects.get_or_create(**{ UserModel.USERNAME_FIELD: username, "defaults": { UserModel.USERNAME_FIELD: username } }) return user else: try: if getattr(settings, "KRB5_USERNAME_MATCH_IEXACT", True): return UserModel.objects.get(**{UserModel.USERNAME_FIELD+"__iexact": username}) else: return UserModel._default_manager.get_by_natural_key(username) except UserModel.DoesNotExist: return None return None def check_password(self, username, password): """The actual password checking logic. Separated from the authenticate code from Django for easier updating""" try: if SUPPORTS_VERIFY: kerberos.checkPassword(username.lower(), password, getattr(settings, "KRB5_SERVICE", ""), getattr(settings, "KRB5_REALM", ""), getattr(settings, "KRB5_VERIFY_KDC", True)) else: kerberos.checkPassword(username.lower(), password, getattr(settings, "KRB5_SERVICE", ""), getattr(settings, "KRB5_REALM", "")) return True except kerberos.BasicAuthError: if getattr(settings, "KRB5_DEBUG", False): logger.exception("Failure during authentication") return False except: if getattr(settings, "KRB5_DEBUG", False): logger.exception("Failure during authentication") # for all other execptions also deny access return False
class KrbBackend(ModelBackend): ''' Django Authentication backend using Kerberos for password checking. ''' def authenticate(self, request, username=None, password=None, **kwargs): pass def check_password(self, username, password): '''The actual password checking logic. Separated from the authenticate code from Django for easier updating''' pass
3
2
23
1
21
1
6
0.12
1
0
0
0
2
0
2
2
52
4
43
5
40
5
33
5
30
6
1
3
12
33
02strich/django-auth-kerberos
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/02strich_django-auth-kerberos/django_auth_kerberos/tests.py
django_auth_kerberos.tests.BasicTest
class BasicTest(unittest.TestCase): def setUp(self): self.sut = KrbBackend() def test_login_success(self): self.assertIsNotNone(self.sut.authenticate( settings.KRB5_TEST_USER, settings.KRB5_TEST_PASSWORD)) def test_login_wrong_password(self): self.assertIsNone(self.sut.authenticate('asdafasd', ''))
class BasicTest(unittest.TestCase): def setUp(self): pass def test_login_success(self): pass def test_login_wrong_password(self): pass
4
0
2
0
2
0
1
0
1
1
1
0
3
1
3
75
9
2
7
5
3
0
7
5
3
1
2
0
3
34
05bit/peewee-async
docs/samples/tornado_sample.py
tornado_sample.RootHandler
class RootHandler(tornado.web.RequestHandler): """Accepts GET and POST methods. POST: create new instance, `name` argument is required GET: get instance by id, `id` argument is required """ async def post(self): name = self.get_argument('name') obj = await TestNameModel.aio_create(name=name) self.write({ 'id': obj.id, 'name': obj.name }) async def get(self): obj_id = self.get_argument('id', None) if not obj_id: self.write("Please provide the 'id' query argument, i.e. ?id=1") return try: obj = await TestNameModel.aio_get(id=obj_id) self.write({ 'id': obj.id, 'name': obj.name, }) except TestNameModel.DoesNotExist: raise tornado.web.HTTPError(404, "Object not found!")
class RootHandler(tornado.web.RequestHandler): '''Accepts GET and POST methods. POST: create new instance, `name` argument is required GET: get instance by id, `id` argument is required ''' async def post(self): pass async def get(self): pass
3
1
11
1
10
0
2
0.19
1
2
1
0
2
0
2
83
29
4
21
7
18
4
15
7
12
3
2
1
4
35
05bit/peewee-async
peewee_async/aio_model.py
peewee_async.aio_model.AioSelectMixin
class AioSelectMixin(AioQueryMixin, peewee.SelectBase): @peewee.database_required async def aio_peek(self, database: AioDatabase, n: int = 1) -> Any: """ Asynchronous version of `peewee.SelectBase.peek <https://docs.peewee-orm.com/en/latest/peewee/api.html#SelectBase.peek>`_ """ async def fetch_results(cursor: CursorProtocol) -> Any: return await fetch_models(cursor, self, n) rows = await database.aio_execute(self, fetch_results=fetch_results) if rows: return rows[0] if n == 1 else rows @peewee.database_required async def aio_scalar( self, database: AioDatabase, as_tuple: bool = False, as_dict: bool = False ) -> Any: """ Asynchronous version of `peewee.SelectBase.scalar <https://docs.peewee-orm.com/en/latest/peewee/api.html#SelectBase.scalar>`_ """ if as_dict: return await self.dicts().aio_peek(database) row = await self.tuples().aio_peek(database) return row[0] if row and not as_tuple else row @peewee.database_required async def aio_first(self, database: AioDatabase, n: int = 1) -> Any: """ Asynchronous version of `peewee.SelectBase.first <https://docs.peewee-orm.com/en/latest/peewee/api.html#SelectBase.first>`_ """ if self._limit != n: # type: ignore self._limit = n return await self.aio_peek(database, n=n) async def aio_get(self, database: Optional[AioDatabase] = None) -> Any: """ Asynchronous version of `peewee.SelectBase.get <https://docs.peewee-orm.com/en/latest/peewee/api.html#SelectBase.get>`_ """ clone = self.paginate(1, 1) try: return (await clone.aio_execute(database))[0] except IndexError: sql, params = clone.sql() raise self.model.DoesNotExist('%s instance matching query does ' 'not exist:\nSQL: %s\nParams: %s' % (clone.model, sql, params)) @peewee.database_required async def aio_count(self, database: AioDatabase, clear_limit: bool = False) -> int: """ Asynchronous version of `peewee.SelectBase.count <https://docs.peewee-orm.com/en/latest/peewee/api.html#SelectBase.count>`_ """ clone = self.order_by().alias('_wrapped') if clear_limit: clone._limit = clone._offset = None try: if clone._having is None and clone._group_by is None and \ clone._windows is None and clone._distinct is None and \ clone._simple_distinct is not True: clone = clone.select(peewee.SQL('1')) except AttributeError: pass return cast( int, await AioSelect([clone], [peewee.fn.COUNT(peewee.SQL('1'))]).aio_scalar(database) ) @peewee.database_required async def aio_exists(self, database: AioDatabase) -> bool: """ Asynchronous version of `peewee.SelectBase.exists <https://docs.peewee-orm.com/en/latest/peewee/api.html#SelectBase.exists>`_ """ clone = self.columns(peewee.SQL('1')) clone._limit = 1 clone._offset = None return bool(await clone.aio_scalar()) def union_all(self, rhs: Any) -> "AioModelCompoundSelectQuery": return AioModelCompoundSelectQuery(self.model, self, 'UNION ALL', rhs) __add__ = union_all def union(self, rhs: Any) -> "AioModelCompoundSelectQuery": return AioModelCompoundSelectQuery(self.model, self, 'UNION', rhs) __or__ = union def intersect(self, rhs: Any) -> "AioModelCompoundSelectQuery": return AioModelCompoundSelectQuery(self.model, self, 'INTERSECT', rhs) __and__ = intersect def except_(self, rhs: Any) -> "AioModelCompoundSelectQuery": return AioModelCompoundSelectQuery(self.model, self, 'EXCEPT', rhs) __sub__ = except_ def aio_prefetch(self, *subqueries: Any, prefetch_type: PREFETCH_TYPE = PREFETCH_TYPE.WHERE) -> Any: """ Asynchronous version of `peewee.ModelSelect.prefetch <https://docs.peewee-orm.com/en/latest/peewee/api.html#ModelSelect.prefetch>`_ """ return aio_prefetch(self, *subqueries, prefetch_type=prefetch_type)
class AioSelectMixin(AioQueryMixin, peewee.SelectBase): @peewee.database_required async def aio_peek(self, database: AioDatabase, n: int = 1) -> Any: ''' Asynchronous version of `peewee.SelectBase.peek <https://docs.peewee-orm.com/en/latest/peewee/api.html#SelectBase.peek>`_ ''' pass async def fetch_results(cursor: CursorProtocol) -> Any: pass @peewee.database_required async def aio_scalar( self, database: AioDatabase, as_tuple: bool = False, as_dict: bool = False ) -> Any: ''' Asynchronous version of `peewee.SelectBase.scalar <https://docs.peewee-orm.com/en/latest/peewee/api.html#SelectBase.scalar>`_ ''' pass @peewee.database_required async def aio_first(self, database: AioDatabase, n: int = 1) -> Any: ''' Asynchronous version of `peewee.SelectBase.first <https://docs.peewee-orm.com/en/latest/peewee/api.html#SelectBase.first>`_ ''' pass async def aio_get(self, database: Optional[AioDatabase] = None) -> Any: ''' Asynchronous version of `peewee.SelectBase.get <https://docs.peewee-orm.com/en/latest/peewee/api.html#SelectBase.get>`_ ''' pass @peewee.database_required async def aio_count(self, database: AioDatabase, clear_limit: bool = False) -> int: ''' Asynchronous version of `peewee.SelectBase.count <https://docs.peewee-orm.com/en/latest/peewee/api.html#SelectBase.count>`_ ''' pass @peewee.database_required async def aio_exists(self, database: AioDatabase) -> bool: ''' Asynchronous version of `peewee.SelectBase.exists <https://docs.peewee-orm.com/en/latest/peewee/api.html#SelectBase.exists>`_ ''' pass def union_all(self, rhs: Any) -> "AioModelCompoundSelectQuery": pass def union_all(self, rhs: Any) -> "AioModelCompoundSelectQuery": pass def intersect(self, rhs: Any) -> "AioModelCompoundSelectQuery": pass def except_(self, rhs: Any) -> "AioModelCompoundSelectQuery": pass def aio_prefetch(self, *subqueries: Any, prefetch_type: PREFETCH_TYPE = PREFETCH_TYPE.WHERE) -> Any: ''' Asynchronous version of `peewee.ModelSelect.prefetch <https://docs.peewee-orm.com/en/latest/peewee/api.html#ModelSelect.prefetch>`_ ''' pass
18
7
8
0
5
2
2
0.42
2
9
4
3
11
1
11
13
113
16
69
34
46
29
52
24
39
4
1
2
21
36
05bit/peewee-async
peewee_async/connection.py
peewee_async.connection.ConnectionContext
class ConnectionContext: def __init__(self, connection: ConnectionProtocol) -> None: self.connection = connection # needs for to know whether begin a transaction or create a savepoint self.transaction_is_opened = False
class ConnectionContext: def __init__(self, connection: ConnectionProtocol) -> None: pass
2
0
4
0
3
1
1
0.25
0
1
1
0
1
2
1
1
5
0
4
4
2
1
4
4
2
1
0
0
1
37
05bit/peewee-async
peewee_async/connection.py
peewee_async.connection.ConnectionContextManager
class ConnectionContextManager: def __init__(self, pool_backend: PoolBackend) -> None: self.pool_backend = pool_backend self.connection_context = connection_context.get() self.resuing_connection = self.connection_context is not None async def __aenter__(self) -> ConnectionProtocol: if self.connection_context is not None: connection = self.connection_context.connection else: connection = await self.pool_backend.acquire() self.connection_context = ConnectionContext(connection) connection_context.set(self.connection_context) return connection async def __aexit__( self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType] ) -> None: if self.resuing_connection is False: if self.connection_context is not None: await self.pool_backend.release(self.connection_context.connection) connection_context.set(None)
class ConnectionContextManager: def __init__(self, pool_backend: PoolBackend) -> None: pass async def __aenter__(self) -> ConnectionProtocol: pass async def __aexit__( self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType] ) -> None: pass
4
0
7
0
7
0
2
0
0
4
3
0
3
3
3
3
25
2
23
13
14
0
17
8
13
3
0
2
6
38
05bit/peewee-async
peewee_async/databases.py
peewee_async.databases.AioDatabase
class AioDatabase(peewee.Database): """Base async database driver providing **single drop-in sync** connection and **async connections pool** interface. :param pool_params: parameters that are passed to the pool Example:: database = PooledPostgresqlExtDatabase( 'database': 'postgres', 'host': '127.0.0.1', 'port':5432, 'password': 'postgres', 'user': 'postgres', 'pool_params': { "minsize": 0, "maxsize": 5, "timeout": 30, 'pool_recycle': 1.5 } ) See also: https://peewee.readthedocs.io/en/latest/peewee/api.html#Database """ _allow_sync = True # whether sync queries are allowed pool_backend_cls: Type[PoolBackend] pool_backend: PoolBackend def __init__(self, *args: Any, **kwargs: Any) -> None: self.pool_params: Dict[str, Any] = {} super().__init__(*args, **kwargs) def init_pool_params_defaults(self) -> None: pass def init_pool_params(self) -> None: self.init_pool_params_defaults() if "min_connections" in self.connect_params or "max_connections" in self.connect_params: warnings.warn( "`min_connections` and `max_connections` are deprecated, use `pool_params` instead.", DeprecationWarning ) self.pool_params.update( { "minsize": self.connect_params.pop("min_connections", 1), "maxsize": self.connect_params.pop("max_connections", 20), } ) pool_params = self.connect_params.pop('pool_params', {}) self.pool_params.update(pool_params) self.pool_params.update(self.connect_params) def init(self, database: Optional[str], **kwargs: Any) -> None: super().init(database, **kwargs) self.init_pool_params() self.pool_backend = self.pool_backend_cls( database=self.database, **self.pool_params ) async def aio_connect(self) -> None: """Creates a connection pool """ if self.deferred: raise Exception('Error, database must be initialized before creating a connection pool') await self.pool_backend.connect() @property def is_connected(self) -> bool: """Checks if pool is connected """ return self.pool_backend.is_connected async def aio_close(self) -> None: """Close pool backend. The pool is closed until you run aio_connect manually.""" if self.deferred: raise Exception('Error, database must be initialized before creating a connection pool') await self.pool_backend.close() @contextlib.asynccontextmanager async def aio_atomic(self) -> AsyncIterator[None]: """Similar to peewee `Database.atomic()` method, but returns asynchronous context manager. """ async with self.aio_connection() as connection: _connection_context = connection_context.get() assert _connection_context is not None begin_transaction = _connection_context.transaction_is_opened is False try: async with Transaction(connection, is_savepoint=begin_transaction is False): _connection_context.transaction_is_opened = True yield finally: if begin_transaction is True: _connection_context.transaction_is_opened = False def set_allow_sync(self, value: bool) -> None: """Allow or forbid sync queries for the database. See also the :meth:`.allow_sync()` context manager. """ self._allow_sync = value @contextlib.contextmanager def allow_sync(self) -> Iterator[None]: """Allow sync queries within context. Close sync connection on exit if connected. Example:: with database.allow_sync(): PageBlock.create_table(True) """ old_allow_sync = self._allow_sync self._allow_sync = True try: yield except: raise finally: self._allow_sync = old_allow_sync self.close() def execute_sql(self, *args: Any, **kwargs: Any) -> Any: """Sync execute SQL query, `allow_sync` must be set to True. """ assert self._allow_sync, ( "Error, sync query is not allowed! Call the `.set_allow_sync()` " "or use the `.allow_sync()` context manager.") if self._allow_sync in (logging.ERROR, logging.WARNING): logging.log( self._allow_sync, "Error, sync query is not allowed: %s %s" % (str(args), str(kwargs)) ) return super().execute_sql(*args, **kwargs) def aio_connection(self) -> ConnectionContextManager: if self.deferred: raise Exception('Error, database must be initialized before creating a connection pool') return ConnectionContextManager(self.pool_backend) async def aio_execute_sql( self, sql: str, params: Optional[List[Any]] = None, fetch_results: Optional[FetchResults] = None ) -> Any: __log__.debug((sql, params)) with peewee.__exception_wrapper__: async with self.aio_connection() as connection: async with connection.cursor() as cursor: await cursor.execute(sql, params or ()) if fetch_results is not None: return await fetch_results(cursor) async def aio_execute(self, query: Any, fetch_results: Optional[FetchResults] = None) -> Any: """Execute *SELECT*, *INSERT*, *UPDATE* or *DELETE* query asyncronously. :param query: peewee query instance created with ``Model.select()``, ``Model.update()`` etc. :param fetch_results: function with cursor param. It let you get data manually and don't need to close cursor It will be closed automatically. :return: result depends on query type, it's the same as for sync `query.execute()` """ ctx = self.get_sql_context() sql, params = ctx.sql(query).query() fetch_results = fetch_results or getattr(query, 'fetch_results', None) return await self.aio_execute_sql(sql, params, fetch_results=fetch_results)
class AioDatabase(peewee.Database): '''Base async database driver providing **single drop-in sync** connection and **async connections pool** interface. :param pool_params: parameters that are passed to the pool Example:: database = PooledPostgresqlExtDatabase( 'database': 'postgres', 'host': '127.0.0.1', 'port':5432, 'password': 'postgres', 'user': 'postgres', 'pool_params': { "minsize": 0, "maxsize": 5, "timeout": 30, 'pool_recycle': 1.5 } ) See also: https://peewee.readthedocs.io/en/latest/peewee/api.html#Database ''' def __init__(self, *args: Any, **kwargs: Any) -> None: pass def init_pool_params_defaults(self) -> None: pass def init_pool_params_defaults(self) -> None: pass def init_pool_params_defaults(self) -> None: pass async def aio_connect(self) -> None: '''Creates a connection pool ''' pass @property def is_connected(self) -> bool: '''Checks if pool is connected ''' pass async def aio_close(self) -> None: '''Close pool backend. The pool is closed until you run aio_connect manually.''' pass @contextlib.asynccontextmanager async def aio_atomic(self) -> AsyncIterator[None]: '''Similar to peewee `Database.atomic()` method, but returns asynchronous context manager. ''' pass def set_allow_sync(self, value: bool) -> None: '''Allow or forbid sync queries for the database. See also the :meth:`.allow_sync()` context manager. ''' pass @contextlib.contextmanager def allow_sync(self) -> Iterator[None]: '''Allow sync queries within context. Close sync connection on exit if connected. Example:: with database.allow_sync(): PageBlock.create_table(True) ''' pass def execute_sql(self, *args: Any, **kwargs: Any) -> Any: '''Sync execute SQL query, `allow_sync` must be set to True. ''' pass def aio_connection(self) -> ConnectionContextManager: pass async def aio_execute_sql( self, sql: str, params: Optional[List[Any]] = None, fetch_results: Optional[FetchResults] = None ) -> Any: pass async def aio_execute_sql( self, sql: str, params: Optional[List[Any]] = None, fetch_results: Optional[FetchResults] = None ) -> Any: '''Execute *SELECT*, *INSERT*, *UPDATE* or *DELETE* query asyncronously. :param query: peewee query instance created with ``Model.select()``, ``Model.update()`` etc. :param fetch_results: function with cursor param. It let you get data manually and don't need to close cursor It will be closed automatically. :return: result depends on query type, it's the same as for sync `query.execute()` ''' pass
18
9
9
1
7
2
2
0.46
1
8
2
3
14
1
14
14
175
27
102
34
79
47
75
23
60
2
1
4
22
39
05bit/peewee-async
peewee_async/databases.py
peewee_async.databases.PooledMySQLDatabase
class PooledMySQLDatabase(AioDatabase, peewee.MySQLDatabase): """MySQL database driver providing **single drop-in sync** connection and **async connections pool** interface. Example:: database = PooledMySQLDatabase( 'database': 'mysql', 'host': '127.0.0.1', 'port': 3306, 'user': 'root', 'password': 'mysql', 'connect_timeout': 30, "pool_params": { "minsize": 0, "maxsize": 5, "pool_recycle": 2 } ) See also: http://peewee.readthedocs.io/en/latest/peewee/api.html#MySQLDatabase """ pool_backend_cls = MysqlPoolBackend def init_pool_params_defaults(self) -> None: self.pool_params.update({"autocommit": True}) def init(self, database: Optional[str], **kwargs: Any) -> None: if not aiomysql: raise Exception("Error, aiomysql is not installed!") super().init(database, **kwargs)
class PooledMySQLDatabase(AioDatabase, peewee.MySQLDatabase): '''MySQL database driver providing **single drop-in sync** connection and **async connections pool** interface. Example:: database = PooledMySQLDatabase( 'database': 'mysql', 'host': '127.0.0.1', 'port': 3306, 'user': 'root', 'password': 'mysql', 'connect_timeout': 30, "pool_params": { "minsize": 0, "maxsize": 5, "pool_recycle": 2 } ) See also: http://peewee.readthedocs.io/en/latest/peewee/api.html#MySQLDatabase ''' def init_pool_params_defaults(self) -> None: pass def init_pool_params_defaults(self) -> None: pass
3
1
3
0
3
0
2
2.38
2
4
0
0
2
0
2
16
32
5
8
4
5
19
8
4
5
2
2
1
3
40
05bit/peewee-async
peewee_async/databases.py
peewee_async.databases.PooledPostgresqlDatabase
class PooledPostgresqlDatabase(AioDatabase, peewee.PostgresqlDatabase): """Extension for `peewee.PostgresqlDatabase` providing extra methods for managing async connection based on aiopg pool backend. Example:: database = PooledPostgresqlExtDatabase( 'database': 'postgres', 'host': '127.0.0.1', 'port':5432, 'password': 'postgres', 'user': 'postgres', 'pool_params': { "minsize": 0, "maxsize": 5, "timeout": 30, 'pool_recycle': 1.5 } ) See also: https://peewee.readthedocs.io/en/latest/peewee/api.html#PostgresqlDatabase """ pool_backend_cls = PostgresqlPoolBackend def init_pool_params_defaults(self) -> None: self.pool_params.update({"enable_json": False, "enable_hstore": False}) def init(self, database: Optional[str], **kwargs: Any) -> None: if not aiopg: raise Exception("Error, aiopg is not installed!") super().init(database, **kwargs)
class PooledPostgresqlDatabase(AioDatabase, peewee.PostgresqlDatabase): '''Extension for `peewee.PostgresqlDatabase` providing extra methods for managing async connection based on aiopg pool backend. Example:: database = PooledPostgresqlExtDatabase( 'database': 'postgres', 'host': '127.0.0.1', 'port':5432, 'password': 'postgres', 'user': 'postgres', 'pool_params': { "minsize": 0, "maxsize": 5, "timeout": 30, 'pool_recycle': 1.5 } ) See also: https://peewee.readthedocs.io/en/latest/peewee/api.html#PostgresqlDatabase ''' def init_pool_params_defaults(self) -> None: pass def init_pool_params_defaults(self) -> None: pass
3
1
3
0
3
0
2
2.38
2
4
0
1
2
0
2
16
34
7
8
4
5
19
8
4
5
2
2
1
3
41
05bit/peewee-async
peewee_async/databases.py
peewee_async.databases.PooledPostgresqlExtDatabase
class PooledPostgresqlExtDatabase( PooledPostgresqlDatabase, ext.PostgresqlExtDatabase ): """PosgtreSQL database extended driver providing **single drop-in sync** connection and **async connections pool** interface based on aiopg pool backend. JSON fields support is enabled by default, HStore supports is disabled by default, but can be enabled through pool_params or with ``register_hstore=False`` argument. See also: https://peewee.readthedocs.io/en/latest/peewee/playhouse.html#PostgresqlExtDatabase """ def init_pool_params_defaults(self) -> None: self.pool_params.update({ "enable_json": True, "enable_hstore": self._register_hstore })
class PooledPostgresqlExtDatabase( PooledPostgresqlDatabase, ext.PostgresqlExtDatabase ): '''PosgtreSQL database extended driver providing **single drop-in sync** connection and **async connections pool** interface based on aiopg pool backend. JSON fields support is enabled by default, HStore supports is disabled by default, but can be enabled through pool_params or with ``register_hstore=False`` argument. See also: https://peewee.readthedocs.io/en/latest/peewee/playhouse.html#PostgresqlExtDatabase ''' def init_pool_params_defaults(self) -> None: pass
2
1
5
0
5
0
1
0.78
2
0
0
0
1
0
1
17
18
2
9
5
4
7
3
2
1
1
3
0
1
42
05bit/peewee-async
peewee_async/databases.py
peewee_async.databases.PsycopgDatabase
class PsycopgDatabase(AioDatabase, Psycopg3Database): """Extension for `peewee.PostgresqlDatabase` providing extra methods for managing async connection based on psycopg3 pool backend. Example:: database = PsycopgDatabase( 'database': 'postgres', 'host': '127.0.0.1', 'port': 5432, 'password': 'postgres', 'user': 'postgres', 'pool_params': { "min_size": 0, "max_size": 5, 'max_lifetime': 15 } ) See also: https://www.psycopg.org/psycopg3/docs/advanced/pool.html """ pool_backend_cls = PsycopgPoolBackend def init(self, database: Optional[str], **kwargs: Any) -> None: if not psycopg: raise Exception("Error, psycopg is not installed!") super().init(database, **kwargs)
class PsycopgDatabase(AioDatabase, Psycopg3Database): '''Extension for `peewee.PostgresqlDatabase` providing extra methods for managing async connection based on psycopg3 pool backend. Example:: database = PsycopgDatabase( 'database': 'postgres', 'host': '127.0.0.1', 'port': 5432, 'password': 'postgres', 'user': 'postgres', 'pool_params': { "min_size": 0, "max_size": 5, 'max_lifetime': 15 } ) See also: https://www.psycopg.org/psycopg3/docs/advanced/pool.html ''' def init(self, database: Optional[str], **kwargs: Any) -> None: pass
2
1
4
0
4
0
2
3
2
4
0
0
1
0
1
15
29
5
6
3
4
18
6
3
4
2
2
1
2
43
05bit/peewee-async
peewee_async/pool.py
peewee_async.pool.MysqlPoolBackend
class MysqlPoolBackend(PoolBackend): """Asynchronous database connection pool based on aiomysql.""" async def create(self) -> None: self.pool = await aiomysql.create_pool( db=self.database, **self.connect_params ) async def acquire(self) -> ConnectionProtocol: if self.pool is None: await self.connect() assert self.pool is not None, "Pool is not connected" return cast(ConnectionProtocol, await self.pool.acquire()) async def release(self, conn: ConnectionProtocol) -> None: assert self.pool is not None, "Pool is not connected" self.pool.release(conn) def has_acquired_connections(self) -> bool: if self.pool is not None: return len(self.pool._used) > 0 return False async def close(self) -> None: if self.pool is not None: self.pool.terminate() await self.pool.wait_closed()
class MysqlPoolBackend(PoolBackend): '''Asynchronous database connection pool based on aiomysql.''' async def create(self) -> None: pass async def acquire(self) -> ConnectionProtocol: pass async def release(self, conn: ConnectionProtocol) -> None: pass def has_acquired_connections(self) -> bool: pass async def close(self) -> None: pass
6
1
4
0
4
0
2
0.05
1
2
1
0
5
1
5
33
27
5
21
7
15
1
19
7
13
2
4
1
8
44
05bit/peewee-async
peewee_async/pool.py
peewee_async.pool.PostgresqlPoolBackend
class PostgresqlPoolBackend(PoolBackend): """Asynchronous database connection pool based on aiopg.""" async def create(self) -> None: if "connect_timeout" in self.connect_params: self.connect_params['timeout'] = self.connect_params.pop("connect_timeout") self.pool = await aiopg.create_pool( database=self.database, **self.connect_params ) async def acquire(self) -> ConnectionProtocol: if self.pool is None: await self.connect() assert self.pool is not None, "Pool is not connected" return cast(ConnectionProtocol, await self.pool.acquire()) async def release(self, conn: ConnectionProtocol) -> None: assert self.pool is not None, "Pool is not connected" self.pool.release(conn) async def close(self) -> None: if self.pool is not None: self.pool.terminate() await self.pool.wait_closed() def has_acquired_connections(self) -> bool: if self.pool is not None: return len(self.pool._used) > 0 return False
class PostgresqlPoolBackend(PoolBackend): '''Asynchronous database connection pool based on aiopg.''' async def create(self) -> None: pass async def acquire(self) -> ConnectionProtocol: pass async def release(self, conn: ConnectionProtocol) -> None: pass async def close(self) -> None: pass def has_acquired_connections(self) -> bool: pass
6
1
5
0
5
0
2
0.04
1
2
1
0
5
1
5
33
30
5
24
7
18
1
21
7
15
2
4
1
9
45
05bit/peewee-async
peewee_async/pool.py
peewee_async.pool.PsycopgPoolBackend
class PsycopgPoolBackend(PoolBackend): """Asynchronous database connection pool based on psycopg + psycopg_pool.""" async def create(self) -> None: params = self.connect_params.copy() pool = psycopg_pool.AsyncConnectionPool( format_dsn( 'postgresql', host=params.pop('host'), port=params.pop('port'), user=params.pop('user'), password=params.pop('password'), path=self.database, ), kwargs={ 'cursor_factory': psycopg.AsyncClientCursor, 'autocommit': True, }, open=False, **params, ) await pool.open() self.pool = pool def has_acquired_connections(self) -> bool: if self.pool is not None: stats = self.pool.get_stats() return stats['pool_size'] > stats['pool_available'] # type: ignore return False async def acquire(self) -> ConnectionProtocol: if self.pool is None: await self.connect() assert self.pool is not None, "Pool is not connected" return cast(ConnectionProtocol, await self.pool.getconn()) async def release(self, conn: ConnectionProtocol) -> None: assert self.pool is not None, "Pool is not connected" await self.pool.putconn(conn) async def close(self) -> None: """Close the pool. Notes the pool does not close active connections""" if self.pool is not None: await self.pool.close()
class PsycopgPoolBackend(PoolBackend): '''Asynchronous database connection pool based on psycopg + psycopg_pool.''' async def create(self) -> None: pass def has_acquired_connections(self) -> bool: pass async def acquire(self) -> ConnectionProtocol: pass async def release(self, conn: ConnectionProtocol) -> None: pass async def close(self) -> None: '''Close the pool. Notes the pool does not close active connections''' pass
6
2
8
0
7
0
2
0.08
1
2
1
0
5
2
5
33
45
6
37
11
31
3
22
10
16
2
4
1
8
46
05bit/peewee-async
peewee_async/result_wrappers.py
peewee_async.result_wrappers.SyncCursorAdapter
class SyncCursorAdapter(object): def __init__(self, rows: List[Any], description: Optional[Sequence[Any]]) -> None: self._rows = rows self.description = description self._idx = 0 def fetchone(self) -> Any: if self._idx >= len(self._rows): return None row = self._rows[self._idx] self._idx += 1 return row def close(self) -> None: pass
class SyncCursorAdapter(object): def __init__(self, rows: List[Any], description: Optional[Sequence[Any]]) -> None: pass def fetchone(self) -> Any: pass def close(self) -> None: pass
4
0
4
0
4
0
1
0
1
1
0
0
3
3
3
3
15
2
13
8
9
0
13
8
9
2
1
1
4
47
05bit/peewee-async
peewee_async/transactions.py
peewee_async.transactions.Transaction
class Transaction: def __init__(self, connection: ConnectionProtocol, is_savepoint: bool = False): self.connection = connection self.savepoint: Optional[str] = None if is_savepoint: self.savepoint = f"PWASYNC__{uuid.uuid4().hex}" @property def is_savepoint(self) -> bool: return self.savepoint is not None async def execute(self, sql: str) -> None: async with self.connection.cursor() as cursor: await cursor.execute(sql) async def begin(self) -> None: sql = "BEGIN" if self.savepoint: sql = f"SAVEPOINT {self.savepoint}" await self.execute(sql) async def __aenter__(self) -> 'Transaction': await self.begin() return self async def __aexit__( self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType] ) -> None: if exc_type is not None: await self.rollback() else: await self.commit() async def commit(self) -> None: sql = "COMMIT" if self.savepoint: sql = f"RELEASE SAVEPOINT {self.savepoint}" await self.execute(sql) async def rollback(self) -> None: sql = "ROLLBACK" if self.savepoint: sql = f"ROLLBACK TO SAVEPOINT {self.savepoint}" await self.execute(sql)
class Transaction: def __init__(self, connection: ConnectionProtocol, is_savepoint: bool = False): pass @property def is_savepoint(self) -> bool: pass async def execute(self, sql: str) -> None: pass async def begin(self) -> None: pass async def __aenter__(self) -> 'Transaction': pass async def __aexit__( self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType] ) -> None: pass async def commit(self) -> None: pass async def rollback(self) -> None: pass
10
0
5
0
5
0
2
0
0
4
1
0
8
2
8
8
49
9
40
21
25
0
33
14
24
2
0
1
13
48
05bit/peewee-async
peewee_async/utils.py
peewee_async.utils.ConnectionProtocol
class ConnectionProtocol(Protocol): def cursor( self, **kwargs: Any ) -> AsyncContextManager[CursorProtocol]: ...
class ConnectionProtocol(Protocol): def cursor( self, **kwargs: Any ) -> AsyncContextManager[CursorProtocol]: pass
2
0
5
0
5
0
1
0
1
2
1
0
1
0
1
25
6
0
6
5
1
0
3
2
1
1
5
0
1
49
05bit/peewee-async
peewee_async/utils.py
peewee_async.utils.CursorProtocol
class CursorProtocol(Protocol): async def fetchone(self) -> Any: ... async def fetchall(self) -> List[Any]: ... async def fetchmany(self, size: int) -> List[Any]: ... @property def lastrowid(self) -> int: ... @property def description(self) -> Optional[Sequence[Any]]: ... @property def rowcount(self) -> int: ... async def execute(self, query: str, *args: Any, **kwargs: Any) -> None: ...
class CursorProtocol(Protocol): async def fetchone(self) -> Any: pass async def fetchall(self) -> List[Any]: pass async def fetchmany(self, size: int) -> List[Any]: pass @property def lastrowid(self) -> int: pass @property def description(self) -> Optional[Sequence[Any]]: pass @property def rowcount(self) -> int: pass async def execute(self, query: str, *args: Any, **kwargs: Any) -> None: pass
11
0
2
0
2
0
1
0
1
3
0
0
7
0
7
31
24
6
18
11
7
0
15
8
7
1
5
0
7
50
05bit/peewee-async
tests/models.py
tests.models.IntegerTestModel
class IntegerTestModel(peewee_async.AioModel): __test__ = False # disable pytest warnings num = peewee.IntegerField()
class IntegerTestModel(peewee_async.AioModel): pass
1
0
0
0
0
0
0
0.33
1
0
0
0
0
0
0
13
3
0
3
3
2
1
3
3
2
0
2
0
0
51
05bit/peewee-async
tests/models.py
tests.models.TestModel
class TestModel(peewee_async.AioModel): __test__ = False # disable pytest warnings text = peewee.CharField(max_length=100, unique=True) data = peewee.TextField(default='') def __str__(self) -> str: return '<%s id=%s> %s' % (self.__class__.__name__, self.id, self.text)
class TestModel(peewee_async.AioModel): def __str__(self) -> str: pass
2
0
2
0
2
0
1
0.17
1
1
0
0
1
0
1
14
7
1
6
5
4
1
6
5
4
1
2
0
1
52
05bit/peewee-async
tests/models.py
tests.models.TestModelAlpha
class TestModelAlpha(peewee_async.AioModel): __test__ = False text = peewee.CharField() def __str__(self) -> str: return '<%s id=%s> %s' % (self.__class__.__name__, self.id, self.text)
class TestModelAlpha(peewee_async.AioModel): def __str__(self) -> str: pass
2
0
2
0
2
0
1
0
1
1
0
0
1
0
1
14
6
1
5
4
3
0
5
4
3
1
2
0
1
53
05bit/peewee-async
tests/models.py
tests.models.TestModelBeta
class TestModelBeta(peewee_async.AioModel): __test__ = False alpha = peewee.ForeignKeyField(TestModelAlpha, backref='betas') text = peewee.CharField() def __str__(self) -> str: return '<%s id=%s> %s' % (self.__class__.__name__, self.id, self.text)
class TestModelBeta(peewee_async.AioModel): def __str__(self) -> str: pass
2
0
2
0
2
0
1
0
1
1
0
0
1
0
1
14
7
1
6
5
4
0
6
5
4
1
2
0
1
54
05bit/peewee-async
tests/test_transaction.py
tests.test_transaction.FakeConnectionError
class FakeConnectionError(Exception): pass
class FakeConnectionError(Exception): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
1
1
0
2
1
1
0
3
0
0
55
05bit/peewee-async
docs/samples/tornado_sample.py
tornado_sample.CreateHandler
class CreateHandler(tornado.web.RequestHandler): async def get(self): loop = asyncio.get_event_loop() task1 = asyncio.Task.current_task() # Just to demonstrate it's None task2 = loop.create_task(self.get_or_create()) obj = await task2 self.write({ 'task1': task1 and id(task1), 'task2': task2 and id(task2), 'obj': str(obj), 'text': "'task1' should be null, " "'task2' should be not null, " "'obj' should be newly created object", }) async def get_or_create(self): obj_id = self.get_argument('id', None) async with self.application.database.aio_atomic(): obj, created = await TestNameModel.aio_get_or_create( id=obj_id, defaults={'name': "TestNameModel id=%s" % obj_id}) return obj
class CreateHandler(tornado.web.RequestHandler): async def get(self): pass async def get_or_create(self): pass
3
0
10
0
10
1
1
0.05
1
2
1
0
2
0
2
83
22
1
21
9
18
1
12
9
9
1
2
1
2
56
05bit/peewee-async
peewee_async/aio_model.py
peewee_async.aio_model.AioSelect
class AioSelect(AioSelectMixin, peewee.Select): pass
class AioSelect(AioSelectMixin, peewee.Select): pass
1
0
0
0
0
0
0
0
2
0
0
0
0
0
0
13
2
0
2
1
1
0
2
1
1
0
2
0
0
57
05bit/peewee-async
docs/samples/tornado_sample.py
tornado_sample.TestNameModel
class TestNameModel(peewee_async.AioModel): name = peewee.CharField() class Meta: database = database def __str__(self): return self.name
class TestNameModel(peewee_async.AioModel): class Meta: def __str__(self): pass
3
0
2
0
2
0
1
0
1
0
0
0
1
0
1
14
7
1
6
5
3
0
6
5
3
1
2
0
1
58
05bit/peewee-async
tests/models.py
tests.models.TestModelGamma
class TestModelGamma(peewee_async.AioModel): __test__ = False text = peewee.CharField() beta = peewee.ForeignKeyField(TestModelBeta, backref='gammas') def __str__(self) -> str: return '<%s id=%s> %s' % (self.__class__.__name__, self.id, self.text)
class TestModelGamma(peewee_async.AioModel): def __str__(self) -> str: pass
2
0
2
0
2
0
1
0
1
1
0
0
1
0
1
14
7
1
6
5
4
0
6
5
4
1
2
0
1
59
05bit/peewee-async
peewee_async/aio_model.py
peewee_async.aio_model.AioModelUpdate
class AioModelUpdate(peewee.ModelUpdate, AioQueryMixin): async def fetch_results(self, cursor: CursorProtocol) -> Union[List[Any], int]: if self._returning: return await fetch_models(cursor, self) return cursor.rowcount
class AioModelUpdate(peewee.ModelUpdate, AioQueryMixin): async def fetch_results(self, cursor: CursorProtocol) -> Union[List[Any], int]: pass
2
0
4
0
4
0
2
0
2
3
1
0
1
0
1
3
6
1
5
2
3
0
5
2
3
2
1
1
2
60
05bit/peewee-async
peewee_async/aio_model.py
peewee_async.aio_model.AioQueryMixin
class AioQueryMixin: @peewee.database_required async def aio_execute(self, database: AioDatabase) -> Any: return await database.aio_execute(self) async def fetch_results(self, cursor: CursorProtocol) -> Any: return await fetch_models(cursor, self)
class AioQueryMixin: @peewee.database_required async def aio_execute(self, database: AioDatabase) -> Any: pass async def fetch_results(self, cursor: CursorProtocol) -> Any: pass
4
0
2
0
2
0
1
0
0
3
2
5
2
0
2
2
7
1
6
4
2
0
5
3
2
1
0
0
2
61
05bit/peewee-async
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/05bit_peewee-async/docs/samples/tornado_sample.py
tornado_sample.TestNameModel.Meta
class Meta: database = database
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
0
0
0
62
05bit/peewee-async
examples/aiohttp_example.py
aiohttp_example.Post
class Post(AioModel): title = CharField(unique=True) key = CharField(unique=True, default=lambda: token_hex(8)) text = TextField() created_at = DateTimeField(index=True, default=datetime.utcnow) class Meta: database = database def __str__(self): return self.title
class Post(AioModel): class Meta: def __str__(self): pass
3
0
2
0
2
0
1
0
1
0
0
0
1
0
1
14
11
2
9
8
6
0
9
8
6
1
2
0
1
63
05bit/peewee-async
tests/models.py
tests.models.UUIDTestModel
class UUIDTestModel(peewee_async.AioModel): id = peewee.UUIDField(primary_key=True, default=uuid.uuid4) text = peewee.CharField() def __str__(self) -> str: return '<%s id=%s> %s' % (self.__class__.__name__, self.id, self.text)
class UUIDTestModel(peewee_async.AioModel): def __str__(self) -> str: pass
2
0
2
0
2
0
1
0
1
1
0
0
1
0
1
14
6
1
5
3
3
0
5
3
3
1
2
0
1
64
05bit/peewee-async
peewee_async/aio_model.py
peewee_async.aio_model.AioModelCompoundSelectQuery
class AioModelCompoundSelectQuery(AioSelectMixin, peewee.ModelCompoundSelectQuery): pass
class AioModelCompoundSelectQuery(AioSelectMixin, peewee.ModelCompoundSelectQuery): pass
1
0
0
0
0
0
0
0
2
0
0
0
0
0
0
13
2
0
2
1
1
0
2
1
1
0
2
0
0
65
05bit/peewee-async
peewee_async/aio_model.py
peewee_async.aio_model.AioModel
class AioModel(peewee.Model): """Async version of **peewee.Model** that allows to execute queries asynchronously with **aio_execute** method Example:: class User(peewee_async.AioModel): username = peewee.CharField(max_length=40, unique=True) await User.select().where(User.username == 'admin').aio_execute() Also it provides async versions of **peewee.Model** shortcuts Example:: user = await User.aio_get(User.username == 'user') """ @classmethod def select(cls, *fields: Any) -> AioModelSelect: is_default = not fields if not fields: fields = cls._meta.sorted_fields return AioModelSelect(cls, fields, is_default=is_default) @classmethod def update(cls, __data: Any = None, **update: Any) -> AioModelUpdate: return AioModelUpdate(cls, cls._normalize_data(__data, update)) @classmethod def insert(cls, __data: Any = None, **insert: Any) -> AioModelInsert: return AioModelInsert(cls, cls._normalize_data(__data, insert)) @classmethod def insert_many(cls, rows: Any, fields: Any = None) -> AioModelInsert: return AioModelInsert(cls, insert=rows, columns=fields) @classmethod def insert_from(cls, query: Any, fields: Any) -> AioModelInsert: columns = [getattr(cls, field) if isinstance(field, str) else field for field in fields] return AioModelInsert(cls, insert=query, columns=columns) @classmethod def raw(cls, sql: Optional[str], *params: Optional[List[Any]]) -> AioModelRaw: return AioModelRaw(cls, sql, params) @classmethod def delete(cls) -> AioModelDelete: return AioModelDelete(cls) async def aio_delete_instance(self, recursive: bool = False, delete_nullable: bool = False) -> int: """ Async version of **peewee.Model.delete_instance** See also: http://docs.peewee-orm.com/en/3.15.3/peewee/api.html#Model.delete_instance """ if recursive: dependencies = self.dependencies(delete_nullable) for query, fk in reversed(list(dependencies)): model = fk.model if fk.null and not delete_nullable: await model.update(**{fk.name: None}).where(query).aio_execute() else: await model.delete().where(query).aio_execute() return cast(int, await type(self).delete().where(self._pk_expr()).aio_execute()) async def aio_save(self, force_insert: bool = False, only: Any =None) -> int: """ Async version of **peewee.Model.save** See also: http://docs.peewee-orm.com/en/3.15.3/peewee/api.html#Model.save """ field_dict = self.__data__.copy() if self._meta.primary_key is not False: pk_field = self._meta.primary_key pk_value = self._pk # type: ignore else: pk_field = pk_value = None if only is not None: field_dict = self._prune_fields(field_dict, only) elif self._meta.only_save_dirty and not force_insert: field_dict = self._prune_fields(field_dict, self.dirty_fields) if not field_dict: self._dirty.clear() return False self._populate_unsaved_relations(field_dict) rows = 1 if self._meta.auto_increment and pk_value is None: field_dict.pop(pk_field.name, None) if pk_value is not None and not force_insert: if self._meta.composite_key: for pk_part_name in pk_field.field_names: field_dict.pop(pk_part_name, None) else: field_dict.pop(pk_field.name, None) if not field_dict: raise ValueError('no data to save!') rows = await self.update(**field_dict).where(self._pk_expr()).aio_execute() elif pk_field is not None: pk = await self.insert(**field_dict).aio_execute() if pk is not None and (self._meta.auto_increment or pk_value is None): self._pk = pk # Although we set the primary-key, do not mark it as dirty. self._dirty.discard(pk_field.name) else: await self.insert(**field_dict).aio_execute() self._dirty -= set(field_dict) # Remove any fields we saved. return rows @classmethod async def aio_get(cls, *query: Any, **filters: Any) -> Self: """Async version of **peewee.Model.get** See also: http://docs.peewee-orm.com/en/3.15.3/peewee/api.html#Model.get """ sq = cls.select() if query: if len(query) == 1 and isinstance(query[0], int): sq = sq.where(cls._meta.primary_key == query[0]) else: sq = sq.where(*query) if filters: sq = sq.filter(**filters) return cast(Self, await sq.aio_get()) @classmethod async def aio_get_or_none(cls, *query: Any, **filters: Any) -> Optional[Self]: """ Async version of **peewee.Model.get_or_none** See also: http://docs.peewee-orm.com/en/3.15.3/peewee/api.html#Model.get_or_none """ try: return await cls.aio_get(*query, **filters) except cls.DoesNotExist: return None @classmethod async def aio_create(cls, **query: Any) -> Self: """ Async version of **peewee.Model.create** See also: http://docs.peewee-orm.com/en/3.15.3/peewee/api.html#Model.create """ inst = cls(**query) await inst.aio_save(force_insert=True) return inst @classmethod async def aio_get_or_create(cls, **kwargs: Any) -> Tuple[Self, bool]: """ Async version of **peewee.Model.get_or_create** See also: http://docs.peewee-orm.com/en/3.15.3/peewee/api.html#Model.get_or_create """ defaults = kwargs.pop('defaults', {}) query = cls.select() for field, value in kwargs.items(): query = query.where(getattr(cls, field) == value) try: return await query.aio_get(), False except cls.DoesNotExist: try: if defaults: kwargs.update(defaults) async with cls._meta.database.aio_atomic(): return await cls.aio_create(**kwargs), True except peewee.IntegrityError as exc: try: return await query.aio_get(), False except cls.DoesNotExist: raise exc
class AioModel(peewee.Model): '''Async version of **peewee.Model** that allows to execute queries asynchronously with **aio_execute** method Example:: class User(peewee_async.AioModel): username = peewee.CharField(max_length=40, unique=True) await User.select().where(User.username == 'admin').aio_execute() Also it provides async versions of **peewee.Model** shortcuts Example:: user = await User.aio_get(User.username == 'user') ''' @classmethod def select(cls, *fields: Any) -> AioModelSelect: pass @classmethod def update(cls, __data: Any = None, **update: Any) -> AioModelUpdate: pass @classmethod def insert(cls, __data: Any = None, **insert: Any) -> AioModelInsert: pass @classmethod def insert_many(cls, rows: Any, fields: Any = None) -> AioModelInsert: pass @classmethod def insert_from(cls, query: Any, fields: Any) -> AioModelInsert: pass @classmethod def raw(cls, sql: Optional[str], *params: Optional[List[Any]]) -> AioModelRaw: pass @classmethod def delete(cls) -> AioModelDelete: pass async def aio_delete_instance(self, recursive: bool = False, delete_nullable: bool = False) -> int: ''' Async version of **peewee.Model.delete_instance** See also: http://docs.peewee-orm.com/en/3.15.3/peewee/api.html#Model.delete_instance ''' pass async def aio_save(self, force_insert: bool = False, only: Any =None) -> int: ''' Async version of **peewee.Model.save** See also: http://docs.peewee-orm.com/en/3.15.3/peewee/api.html#Model.save ''' pass @classmethod async def aio_get(cls, *query: Any, **filters: Any) -> Self: '''Async version of **peewee.Model.get** See also: http://docs.peewee-orm.com/en/3.15.3/peewee/api.html#Model.get ''' pass @classmethod async def aio_get_or_none(cls, *query: Any, **filters: Any) -> Optional[Self]: ''' Async version of **peewee.Model.get_or_none** See also: http://docs.peewee-orm.com/en/3.15.3/peewee/api.html#Model.get_or_none ''' pass @classmethod async def aio_create(cls, **query: Any) -> Self: ''' Async version of **peewee.Model.create** See also: http://docs.peewee-orm.com/en/3.15.3/peewee/api.html#Model.create ''' pass @classmethod async def aio_get_or_create(cls, **kwargs: Any) -> Tuple[Self, bool]: ''' Async version of **peewee.Model.get_or_create** See also: http://docs.peewee-orm.com/en/3.15.3/peewee/api.html#Model.get_or_create ''' pass
25
7
11
1
8
2
3
0.37
1
14
5
11
2
1
13
13
185
30
115
43
90
42
95
31
81
12
1
3
38
66
05bit/peewee-async
peewee_async/aio_model.py
peewee_async.aio_model.AioModelInsert
class AioModelInsert(peewee.ModelInsert, AioQueryMixin): async def fetch_results(self, cursor: CursorProtocol) -> Union[List[Any], Any, int]: if self._returning is not None and len(self._returning) > 1: return await fetch_models(cursor, self) if self._returning: row = await cursor.fetchone() return row[0] if row else None else: return cursor.lastrowid
class AioModelInsert(peewee.ModelInsert, AioQueryMixin): async def fetch_results(self, cursor: CursorProtocol) -> Union[List[Any], Any, int]: pass
2
0
9
1
8
0
4
0
2
3
1
0
1
0
1
3
10
1
9
3
7
0
8
3
6
4
1
1
4
67
05bit/peewee-async
peewee_async/aio_model.py
peewee_async.aio_model.AioModelRaw
class AioModelRaw(peewee.ModelRaw, AioQueryMixin): pass
class AioModelRaw(peewee.ModelRaw, AioQueryMixin): pass
1
0
0
0
0
0
0
0
2
0
0
0
0
0
0
2
2
0
2
1
1
0
2
1
1
0
1
0
0
68
05bit/peewee-async
peewee_async/aio_model.py
peewee_async.aio_model.AioModelSelect
class AioModelSelect(AioSelectMixin, peewee.ModelSelect): """Asynchronous version of **peewee.ModelSelect** that provides async versions of ModelSelect methods """ pass
class AioModelSelect(AioSelectMixin, peewee.ModelSelect): '''Asynchronous version of **peewee.ModelSelect** that provides async versions of ModelSelect methods ''' pass
1
1
0
0
0
0
0
1
2
0
0
0
0
0
0
13
4
0
2
1
1
2
2
1
1
0
2
0
0
69
05bit/peewee-async
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/05bit_peewee-async/tests/models.py
tests.models.CompositeTestModel.Meta
class Meta: primary_key = peewee.CompositeKey('task_id', 'product_type')
class Meta: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
0
0
0
70
05bit/peewee-async
peewee_async/aio_model.py
peewee_async.aio_model.AioModelDelete
class AioModelDelete(peewee.ModelDelete, AioQueryMixin): async def fetch_results(self, cursor: CursorProtocol) -> Union[List[Any], int]: if self._returning: return await fetch_models(cursor, self) return cursor.rowcount
class AioModelDelete(peewee.ModelDelete, AioQueryMixin): async def fetch_results(self, cursor: CursorProtocol) -> Union[List[Any], int]: pass
2
0
4
0
4
0
2
0
2
3
1
0
1
0
1
3
5
0
5
2
3
0
5
2
3
2
1
1
2
71
0compute/xtraceback
0compute_xtraceback/test_support/python/3.1.5/test/test_traceback.py
test.test_traceback.SyntaxTracebackCases
class SyntaxTracebackCases(unittest.TestCase): # For now, a very minimal set of tests. I want to be sure that # formatting of SyntaxErrors works based on changes for 2.1. def get_exception_format(self, func, exc): try: func() except exc as value: return traceback.format_exception_only(exc, value) else: raise ValueError("call did not raise exception") def syntax_error_with_caret(self): compile("def fact(x):\n\treturn x!\n", "?", "exec") def syntax_error_with_caret_2(self): compile("1 +\n", "?", "exec") def syntax_error_without_caret(self): # XXX why doesn't compile raise the same traceback? import test.badsyntax_nocaret def syntax_error_bad_indentation(self): compile("def spam():\n print(1)\n print(2)", "?", "exec") def test_caret(self): err = self.get_exception_format(self.syntax_error_with_caret, SyntaxError) self.assertEqual(len(err), 4) self.assertTrue(err[1].strip() == "return x!") self.assertTrue("^" in err[2]) # third line has caret self.assertEqual(err[1].find("!"), err[2].find("^")) # in the right place err = self.get_exception_format(self.syntax_error_with_caret_2, SyntaxError) self.assertTrue("^" in err[2]) # third line has caret self.assertTrue(err[2].count('\n') == 1) # and no additional newline self.assertTrue(err[1].find("+") == err[2].find("^")) # in the right place def test_nocaret(self): if is_jython: # jython adds a caret in this case (why shouldn't it?) return err = self.get_exception_format(self.syntax_error_without_caret, SyntaxError) self.assertEqual(len(err), 3) self.assertTrue(err[1].strip() == "[x for x in x] = x") def test_bad_indentation(self): err = self.get_exception_format(self.syntax_error_bad_indentation, IndentationError) self.assertEqual(len(err), 4) self.assertEqual(err[1].strip(), "print(2)") self.assertTrue("^" in err[2]) self.assertEqual(err[1].find(")"), err[2].find("^")) def test_base_exception(self): # Test that exceptions derived from BaseException are formatted right e = KeyboardInterrupt() lst = traceback.format_exception_only(e.__class__, e) self.assertEqual(lst, ['KeyboardInterrupt\n']) def test_format_exception_only_bad__str__(self): class X(Exception): def __str__(self): 1/0 err = traceback.format_exception_only(X, X()) self.assertEqual(len(err), 1) str_value = '<unprintable %s object>' % X.__name__ if X.__module__ in ('__main__', 'builtins'): str_name = X.__name__ else: str_name = '.'.join([X.__module__, X.__name__]) self.assertEqual(err[0], "%s: %s\n" % (str_name, str_value)) def test_without_exception(self): err = traceback.format_exception_only(None, None) self.assertEqual(err, ['None\n']) def test_encoded_file(self): # Test that tracebacks are correctly printed for encoded source files: # - correct line number (Issue2384) # - respect file encoding (Issue3975) import tempfile, sys, subprocess, os # The spawned subprocess has its stdout redirected to a PIPE, and its # encoding may be different from the current interpreter, on Windows # at least. process = subprocess.Popen([sys.executable, "-c", "import sys; print(sys.stdout.encoding)"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, stderr = process.communicate() output_encoding = str(stdout, 'ascii').splitlines()[0] def do_test(firstlines, message, charset, lineno): # Raise the message in a subprocess, and catch the output try: output = open(TESTFN, "w", encoding=charset) output.write("""{0}if 1: import traceback; raise RuntimeError('{1}') """.format(firstlines, message)) output.close() process = subprocess.Popen([sys.executable, TESTFN], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, stderr = process.communicate() stdout = stdout.decode(output_encoding).splitlines() finally: unlink(TESTFN) # The source lines are encoded with the 'backslashreplace' handler encoded_message = message.encode(output_encoding, 'backslashreplace') # and we just decoded them with the output_encoding. message_ascii = encoded_message.decode(output_encoding) err_line = "raise RuntimeError('{0}')".format(message_ascii) err_msg = "RuntimeError: {0}".format(message_ascii) self.assertTrue(("line %s" % lineno) in stdout[1], "Invalid line number: {0!r} instead of {1}".format( stdout[1], lineno)) self.assertTrue(stdout[2].endswith(err_line), "Invalid traceback line: {0!r} instead of {1!r}".format( stdout[2], err_line)) self.assertTrue(stdout[3] == err_msg, "Invalid error message: {0!r} instead of {1!r}".format( stdout[3], err_msg)) do_test("", "foo", "ascii", 3) for charset in ("ascii", "iso-8859-1", "utf-8", "GBK"): if charset == "ascii": text = "foo" elif charset == "GBK": text = "\u4E02\u5100" else: text = "h\xe9 ho" do_test("# coding: {0}\n".format(charset), text, charset, 4) do_test("#!shebang\n# coding: {0}\n".format(charset), text, charset, 5)
class SyntaxTracebackCases(unittest.TestCase): def get_exception_format(self, func, exc): pass def syntax_error_with_caret(self): pass def syntax_error_with_caret_2(self): pass def syntax_error_without_caret(self): pass def syntax_error_bad_indentation(self): pass def test_caret(self): pass def test_nocaret(self): pass def test_bad_indentation(self): pass def test_base_exception(self): pass def test_format_exception_only_bad__str__(self): pass class X(Exception): def __str__(self): pass def test_without_exception(self): pass def test_encoded_file(self): pass def do_test(firstlines, message, charset, lineno): pass
16
0
12
1
10
2
1
0.19
1
7
1
0
12
0
12
84
142
19
109
40
91
21
85
39
67
4
2
2
20
72
0compute/xtraceback
0compute_xtraceback/test_support/python/3.3.0/test/test_traceback.py
test.test_traceback.SyntaxTracebackCases
class SyntaxTracebackCases(unittest.TestCase): # For now, a very minimal set of tests. I want to be sure that # formatting of SyntaxErrors works based on changes for 2.1. def get_exception_format(self, func, exc): try: func() except exc as value: return traceback.format_exception_only(exc, value) else: raise ValueError("call did not raise exception") def syntax_error_with_caret(self): compile("def fact(x):\n\treturn x!\n", "?", "exec") def syntax_error_with_caret_2(self): compile("1 +\n", "?", "exec") def syntax_error_bad_indentation(self): compile("def spam():\n print(1)\n print(2)", "?", "exec") def test_caret(self): err = self.get_exception_format(self.syntax_error_with_caret, SyntaxError) self.assertEqual(len(err), 4) self.assertTrue(err[1].strip() == "return x!") self.assertIn("^", err[2]) # third line has caret self.assertEqual(err[1].find("!"), err[2].find("^")) # in the right place err = self.get_exception_format(self.syntax_error_with_caret_2, SyntaxError) self.assertIn("^", err[2]) # third line has caret self.assertTrue(err[2].count('\n') == 1) # and no additional newline self.assertTrue(err[1].find("+") == err[2].find("^")) # in the right place def test_nocaret(self): exc = SyntaxError("error", ("x.py", 23, None, "bad syntax")) err = traceback.format_exception_only(SyntaxError, exc) self.assertEqual(len(err), 3) self.assertEqual(err[1].strip(), "bad syntax") def test_bad_indentation(self): err = self.get_exception_format(self.syntax_error_bad_indentation, IndentationError) self.assertEqual(len(err), 4) self.assertEqual(err[1].strip(), "print(2)") self.assertIn("^", err[2]) self.assertEqual(err[1].find(")"), err[2].find("^")) def test_base_exception(self): # Test that exceptions derived from BaseException are formatted right e = KeyboardInterrupt() lst = traceback.format_exception_only(e.__class__, e) self.assertEqual(lst, ['KeyboardInterrupt\n']) def test_format_exception_only_bad__str__(self): class X(Exception): def __str__(self): 1/0 err = traceback.format_exception_only(X, X()) self.assertEqual(len(err), 1) str_value = '<unprintable %s object>' % X.__name__ if X.__module__ in ('__main__', 'builtins'): str_name = X.__name__ else: str_name = '.'.join([X.__module__, X.__name__]) self.assertEqual(err[0], "%s: %s\n" % (str_name, str_value)) def test_without_exception(self): err = traceback.format_exception_only(None, None) self.assertEqual(err, ['None\n']) def test_encoded_file(self): # Test that tracebacks are correctly printed for encoded source files: # - correct line number (Issue2384) # - respect file encoding (Issue3975) import tempfile, sys, subprocess, os # The spawned subprocess has its stdout redirected to a PIPE, and its # encoding may be different from the current interpreter, on Windows # at least. process = subprocess.Popen([sys.executable, "-c", "import sys; print(sys.stdout.encoding)"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, stderr = process.communicate() output_encoding = str(stdout, 'ascii').splitlines()[0] def do_test(firstlines, message, charset, lineno): # Raise the message in a subprocess, and catch the output try: output = open(TESTFN, "w", encoding=charset) output.write("""{0}if 1: import traceback; raise RuntimeError('{1}') """.format(firstlines, message)) output.close() process = subprocess.Popen([sys.executable, TESTFN], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, stderr = process.communicate() stdout = stdout.decode(output_encoding).splitlines() finally: unlink(TESTFN) # The source lines are encoded with the 'backslashreplace' handler encoded_message = message.encode(output_encoding, 'backslashreplace') # and we just decoded them with the output_encoding. message_ascii = encoded_message.decode(output_encoding) err_line = "raise RuntimeError('{0}')".format(message_ascii) err_msg = "RuntimeError: {0}".format(message_ascii) self.assertIn(("line %s" % lineno), stdout[1], "Invalid line number: {0!r} instead of {1}".format( stdout[1], lineno)) self.assertTrue(stdout[2].endswith(err_line), "Invalid traceback line: {0!r} instead of {1!r}".format( stdout[2], err_line)) self.assertTrue(stdout[3] == err_msg, "Invalid error message: {0!r} instead of {1!r}".format( stdout[3], err_msg)) do_test("", "foo", "ascii", 3) for charset in ("ascii", "iso-8859-1", "utf-8", "GBK"): if charset == "ascii": text = "foo" elif charset == "GBK": text = "\u4E02\u5100" else: text = "h\xe9 ho" do_test("# coding: {0}\n".format(charset), text, charset, 4) do_test("#!shebang\n# coding: {0}\n".format(charset), text, charset, 5)
class SyntaxTracebackCases(unittest.TestCase): def get_exception_format(self, func, exc): pass def syntax_error_with_caret(self): pass def syntax_error_with_caret_2(self): pass def syntax_error_bad_indentation(self): pass def test_caret(self): pass def test_nocaret(self): pass def test_bad_indentation(self): pass def test_base_exception(self): pass def test_format_exception_only_bad__str__(self): pass class X(Exception): def __str__(self): pass def test_without_exception(self): pass def test_encoded_file(self): pass def do_test(firstlines, message, charset, lineno): pass
15
0
12
1
10
2
1
0.18
1
7
1
0
11
0
11
83
135
18
105
39
89
19
82
38
66
4
2
2
18
73
0compute/xtraceback
0compute_xtraceback/test_support/python/3.3.0/test/test_traceback.py
test.test_traceback.SyntaxTracebackCases
class SyntaxTracebackCases(unittest.TestCase): # For now, a very minimal set of tests. I want to be sure that # formatting of SyntaxErrors works based on changes for 2.1. def get_exception_format(self, func, exc): try: func() except exc as value: return traceback.format_exception_only(exc, value) else: raise ValueError("call did not raise exception") def syntax_error_with_caret(self): compile("def fact(x):\n\treturn x!\n", "?", "exec") def syntax_error_with_caret_2(self): compile("1 +\n", "?", "exec") def syntax_error_bad_indentation(self): compile("def spam():\n print(1)\n print(2)", "?", "exec") def test_caret(self): err = self.get_exception_format(self.syntax_error_with_caret, SyntaxError) self.assertEqual(len(err), 4) self.assertTrue(err[1].strip() == "return x!") self.assertIn("^", err[2]) # third line has caret self.assertEqual(err[1].find("!"), err[2].find("^")) # in the right place err = self.get_exception_format(self.syntax_error_with_caret_2, SyntaxError) self.assertIn("^", err[2]) # third line has caret self.assertTrue(err[2].count('\n') == 1) # and no additional newline self.assertTrue(err[1].find("+") == err[2].find("^")) # in the right place def test_nocaret(self): exc = SyntaxError("error", ("x.py", 23, None, "bad syntax")) err = traceback.format_exception_only(SyntaxError, exc) self.assertEqual(len(err), 3) self.assertEqual(err[1].strip(), "bad syntax") def test_bad_indentation(self): err = self.get_exception_format(self.syntax_error_bad_indentation, IndentationError) self.assertEqual(len(err), 4) self.assertEqual(err[1].strip(), "print(2)") self.assertIn("^", err[2]) self.assertEqual(err[1].find(")"), err[2].find("^")) def test_base_exception(self): # Test that exceptions derived from BaseException are formatted right e = KeyboardInterrupt() lst = traceback.format_exception_only(e.__class__, e) self.assertEqual(lst, ['KeyboardInterrupt\n']) def test_format_exception_only_bad__str__(self): class X(Exception): def __str__(self): 1/0 err = traceback.format_exception_only(X, X()) self.assertEqual(len(err), 1) str_value = '<unprintable %s object>' % X.__name__ if X.__module__ in ('__main__', 'builtins'): str_name = X.__name__ else: str_name = '.'.join([X.__module__, X.__name__]) self.assertEqual(err[0], "%s: %s\n" % (str_name, str_value)) def test_without_exception(self): err = traceback.format_exception_only(None, None) self.assertEqual(err, ['None\n']) def test_encoded_file(self): # Test that tracebacks are correctly printed for encoded source files: # - correct line number (Issue2384) # - respect file encoding (Issue3975) import tempfile, sys, subprocess, os # The spawned subprocess has its stdout redirected to a PIPE, and its # encoding may be different from the current interpreter, on Windows # at least. process = subprocess.Popen([sys.executable, "-c", "import sys; print(sys.stdout.encoding)"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, stderr = process.communicate() output_encoding = str(stdout, 'ascii').splitlines()[0] def do_test(firstlines, message, charset, lineno): # Raise the message in a subprocess, and catch the output try: output = open(TESTFN, "w", encoding=charset) output.write("""{0}if 1: import traceback; raise RuntimeError('{1}') """.format(firstlines, message)) output.close() process = subprocess.Popen([sys.executable, TESTFN], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, stderr = process.communicate() stdout = stdout.decode(output_encoding).splitlines() finally: unlink(TESTFN) # The source lines are encoded with the 'backslashreplace' handler encoded_message = message.encode(output_encoding, 'backslashreplace') # and we just decoded them with the output_encoding. message_ascii = encoded_message.decode(output_encoding) err_line = "raise RuntimeError('{0}')".format(message_ascii) err_msg = "RuntimeError: {0}".format(message_ascii) self.assertIn(("line %s" % lineno), stdout[1], "Invalid line number: {0!r} instead of {1}".format( stdout[1], lineno)) self.assertTrue(stdout[2].endswith(err_line), "Invalid traceback line: {0!r} instead of {1!r}".format( stdout[2], err_line)) self.assertTrue(stdout[3] == err_msg, "Invalid error message: {0!r} instead of {1!r}".format( stdout[3], err_msg)) do_test("", "foo", "ascii", 3) for charset in ("ascii", "iso-8859-1", "utf-8", "GBK"): if charset == "ascii": text = "foo" elif charset == "GBK": text = "\u4E02\u5100" else: text = "h\xe9 ho" do_test("# coding: {0}\n".format(charset), text, charset, 4) do_test("#!shebang\n# coding: {0}\n".format(charset), text, charset, 5)
class SyntaxTracebackCases(unittest.TestCase): def get_exception_format(self, func, exc): pass def syntax_error_with_caret(self): pass def syntax_error_with_caret_2(self): pass def syntax_error_bad_indentation(self): pass def test_caret(self): pass def test_nocaret(self): pass def test_bad_indentation(self): pass def test_base_exception(self): pass def test_format_exception_only_bad__str__(self): pass class X(Exception): def __str__(self): pass def test_without_exception(self): pass def test_encoded_file(self): pass def do_test(firstlines, message, charset, lineno): pass
15
0
12
1
10
2
1
0.18
1
7
1
0
11
0
11
83
135
18
105
39
89
19
82
38
66
4
2
2
18
74
0compute/xtraceback
0compute_xtraceback/test_support/python/3.3.0/test/test_traceback.py
test.test_traceback.PyExcReportingTests
class PyExcReportingTests(BaseExceptionReportingTests, unittest.TestCase): # # This checks reporting through the 'traceback' module, with both # format_exception() and print_exception(). # def get_report(self, e): e = self.get_exception(e) s = ''.join( traceback.format_exception(type(e), e, e.__traceback__)) with captured_output("stderr") as sio: traceback.print_exception(type(e), e, e.__traceback__) self.assertEqual(sio.getvalue(), s) return s
class PyExcReportingTests(BaseExceptionReportingTests, unittest.TestCase): def get_report(self, e): pass
2
0
8
0
8
0
1
0.44
2
1
0
0
1
0
1
82
14
1
9
4
7
4
8
3
6
1
2
1
1
75
0compute/xtraceback
0compute_xtraceback/test_support/python/3.3.0/test/test_traceback.py
test.test_traceback.PyExcReportingTests
class PyExcReportingTests(BaseExceptionReportingTests, unittest.TestCase): # # This checks reporting through the 'traceback' module, with both # format_exception() and print_exception(). # def get_report(self, e): e = self.get_exception(e) s = ''.join( traceback.format_exception(type(e), e, e.__traceback__)) with captured_output("stderr") as sio: traceback.print_exception(type(e), e, e.__traceback__) self.assertEqual(sio.getvalue(), s) return s
class PyExcReportingTests(BaseExceptionReportingTests, unittest.TestCase): def get_report(self, e): pass
2
0
8
0
8
0
1
0.44
2
1
0
0
1
0
1
82
14
1
9
4
7
4
8
3
6
1
2
1
1
76
0compute/xtraceback
0compute_xtraceback/test_support/python/3.3.0/test/test_traceback.py
test.test_traceback.PyExcReportingTests
class PyExcReportingTests(BaseExceptionReportingTests, unittest.TestCase): # # This checks reporting through the 'traceback' module, with both # format_exception() and print_exception(). # def get_report(self, e): e = self.get_exception(e) s = ''.join( traceback.format_exception(type(e), e, e.__traceback__)) with captured_output("stderr") as sio: traceback.print_exception(type(e), e, e.__traceback__) self.assertEqual(sio.getvalue(), s) return s
class PyExcReportingTests(BaseExceptionReportingTests, unittest.TestCase): def get_report(self, e): pass
2
0
8
0
8
0
1
0.44
2
1
0
0
1
0
1
83
14
1
9
4
7
4
8
3
6
1
2
1
1
77
0compute/xtraceback
0compute_xtraceback/test_support/python/3.3.0/test/test_traceback.py
test.test_traceback.TracebackFormatTests
class TracebackFormatTests(unittest.TestCase): def test_traceback_format(self): try: raise KeyError('blah') except KeyError: type_, value, tb = sys.exc_info() traceback_fmt = 'Traceback (most recent call last):\n' + \ ''.join(traceback.format_tb(tb)) file_ = StringIO() traceback_print(tb, file_) python_fmt = file_.getvalue() else: raise Error("unable to create test traceback string") # Make sure that Python and the traceback module format the same thing self.assertEqual(traceback_fmt, python_fmt) # Make sure that the traceback is properly indented. tb_lines = python_fmt.splitlines() self.assertEqual(len(tb_lines), 3) banner, location, source_line = tb_lines self.assertTrue(banner.startswith('Traceback')) self.assertTrue(location.startswith(' File')) self.assertTrue(source_line.startswith(' raise'))
class TracebackFormatTests(unittest.TestCase): def test_traceback_format(self): pass
2
0
23
2
19
2
2
0.1
1
1
0
0
1
0
1
73
25
3
20
8
18
2
19
8
17
2
2
1
2
78
0compute/xtraceback
0compute_xtraceback/test_support/python/3.3.0/test/test_traceback.py
test.test_traceback.TracebackFormatTests
class TracebackFormatTests(unittest.TestCase): def test_traceback_format(self): try: raise KeyError('blah') except KeyError: type_, value, tb = sys.exc_info() traceback_fmt = 'Traceback (most recent call last):\n' + \ ''.join(traceback.format_tb(tb)) file_ = StringIO() traceback_print(tb, file_) python_fmt = file_.getvalue() else: raise Error("unable to create test traceback string") # Make sure that Python and the traceback module format the same thing self.assertEqual(traceback_fmt, python_fmt) # Make sure that the traceback is properly indented. tb_lines = python_fmt.splitlines() self.assertEqual(len(tb_lines), 3) banner, location, source_line = tb_lines self.assertTrue(banner.startswith('Traceback')) self.assertTrue(location.startswith(' File')) self.assertTrue(source_line.startswith(' raise'))
class TracebackFormatTests(unittest.TestCase): def test_traceback_format(self): pass
2
0
23
2
19
2
2
0.1
1
2
0
0
1
0
1
73
25
3
20
8
18
2
19
8
17
2
2
1
2
79
0compute/xtraceback
0compute_xtraceback/test_support/python/3.3.0/test/test_traceback.py
test.test_traceback.TracebackFormatTests
class TracebackFormatTests(unittest.TestCase): def test_traceback_format(self): try: raise KeyError('blah') except KeyError: type_, value, tb = sys.exc_info() traceback_fmt = 'Traceback (most recent call last):\n' + \ ''.join(traceback.format_tb(tb)) file_ = StringIO() traceback_print(tb, file_) python_fmt = file_.getvalue() else: raise Error("unable to create test traceback string") # Make sure that Python and the traceback module format the same thing self.assertEqual(traceback_fmt, python_fmt) # Make sure that the traceback is properly indented. tb_lines = python_fmt.splitlines() self.assertEqual(len(tb_lines), 3) banner, location, source_line = tb_lines self.assertTrue(banner.startswith('Traceback')) self.assertTrue(location.startswith(' File')) self.assertTrue(source_line.startswith(' raise'))
class TracebackFormatTests(unittest.TestCase): def test_traceback_format(self): pass
2
0
23
2
19
2
2
0.1
1
2
0
0
1
0
1
73
25
3
20
8
18
2
19
8
17
2
2
1
2
80
0compute/xtraceback
0compute_xtraceback/test_support/python/3.3.0/test/test_traceback.py
test.test_traceback.TracebackFormatTests
class TracebackFormatTests(unittest.TestCase): def test_traceback_format(self): try: raise KeyError('blah') except KeyError: type_, value, tb = sys.exc_info() traceback_fmt = 'Traceback (most recent call last):\n' + \ ''.join(traceback.format_tb(tb)) file_ = StringIO() traceback_print(tb, file_) python_fmt = file_.getvalue() else: raise Error("unable to create test traceback string") # Make sure that Python and the traceback module format the same thing self.assertEqual(traceback_fmt, python_fmt) # Make sure that the traceback is properly indented. tb_lines = python_fmt.splitlines() self.assertEqual(len(tb_lines), 3) banner, location, source_line = tb_lines self.assertTrue(banner.startswith('Traceback')) self.assertTrue(location.startswith(' File')) self.assertTrue(source_line.startswith(' raise'))
class TracebackFormatTests(unittest.TestCase): def test_traceback_format(self): pass
2
0
23
2
19
2
2
0.1
1
2
0
0
1
0
1
73
25
3
20
8
18
2
19
8
17
2
2
1
2
81
0compute/xtraceback
0compute_xtraceback/xtraceback/loggingcompat.py
xtraceback.loggingcompat.LoggingCompat
class LoggingCompat(Stacked): def __init__(self, handler, tbcompat, **options): super(LoggingCompat, self).__init__() self.handler = handler self.tbcompat = tbcompat self.options = options formatter = self.handler.formatter # this is shit but we're stuck with the stdlib implementation since # it caches the result of formatException which we don't want to do # as it will screw up other formatters who are expecting a regular # traceback _format = formatter.format def format(record): record.exc_text = None formatted = _format(record) record.exc_text = None return formatted self._register_patch(formatter, "format", format) self._register_patch(formatter, "formatException", self.formatException) def formatException(self, ei): return str(self.tbcompat._factory(*ei, **self.options))
class LoggingCompat(Stacked): def __init__(self, handler, tbcompat, **options): pass def format(record): pass def formatException(self, ei): pass
4
0
10
2
7
1
1
0.22
1
2
0
0
2
3
2
2
29
7
18
10
14
4
17
10
13
1
1
0
3
82
0compute/xtraceback
0compute_xtraceback/xtraceback/moduleshim.py
xtraceback.moduleshim.ModuleShim
class ModuleShim(object): def __init__(self, options, target): self.options = options self.target = target def __repr__(self): package = False try: filename = inspect.getsourcefile(self.target) except TypeError: filename = None if filename is not None: if os.path.basename(filename) == "__init__.py": package = True filename = os.path.dirname(filename) filename = format_filename(self.options, filename) if filename is None: return repr(self.target) return "<%s '%s' from=%r>" % (package and "package" or "module", self.target.__name__, filename)
class ModuleShim(object): def __init__(self, options, target): pass def __repr__(self): pass
3
0
10
0
10
0
3
0
1
1
0
0
2
2
2
2
22
2
20
7
17
0
18
7
15
5
1
2
6
End of preview. Expand in Data Studio

๐Ÿ“˜ Data Dictionary for the Curated Class-level Dataset

Field Description
id A unique identifier for each data point, starting from 0.
repository_name Name of the GitHub repository from which the class was extracted.
file_path Full path to the file containing the class within the repository.
class_name Name of the class defined in the corresponding file.
human_written_code Full source code of the human-written class, including all docstrings.
class_skeleton Extracted skeleton of the class, including class and method signatures along with associated docstrings (if present).
total_program_units Total number of program units (i.e., classes and methods) within the class skeleton.
total_doc_str Number of program units in the class skeleton that contain associated docstrings.
AvgCountLine Average number of lines per class.
AvgCountLineBlank Average number of blank lines per class.
AvgCountLineCode Average number of code lines per class (excluding comments and blanks).
AvgCountLineComment Average number of comment lines per class.
AvgCyclomatic Average cyclomatic complexity across methods in the class.
CommentToCodeRatio Ratio of comment lines to code lines in the class.
CountClassBase Number of base classes (i.e., direct superclasses).
CountClassCoupled Number of other classes referenced (coupled) by this class.
CountClassCoupledModified Number of coupled classes after removing standard library dependencies.
CountClassDerived Number of classes that inherit from this class.
CountDeclInstanceMethod Number of instance methods declared in the class.
CountDeclInstanceVariable Number of instance variables declared in the class.
CountDeclMethod Number of methods declared in the class (excluding inherited ones).
CountDeclMethodAll Total number of declared methods, including inherited ones.
CountLine Total number of lines in the class.
CountLineBlank Number of blank lines in the class.
CountLineCode Number of executable code lines in the class.
CountLineCodeDecl Number of declaration lines in the class.
CountLineCodeExe Number of executable statement lines in the class.
CountLineComment Number of comment lines in the class.
CountStmt Total number of statements in the class.
CountStmtDecl Number of declaration statements in the class.
CountStmtExe Number of executable statements in the class.
MaxCyclomatic Maximum cyclomatic complexity among all methods in the class.
MaxInheritanceTree Maximum depth of the class in the inheritance hierarchy.
MaxNesting Maximum level of nested control structures in the class.
SumCyclomatic Sum of cyclomatic complexity across all methods in the class.

If you use this dataset, please cite:

@article{rahman2025large,
  title={A Large-scale Class-level Benchmark Dataset for Code Generation with LLMs},
  author={Rahman, Musfiqur and Khatoonabadi, SayedHassan and Shihab, Emad},
  journal={arXiv preprint arXiv:2504.15564},
  year={2025}
}
Downloads last month
76