prompt_id int64 0 941 | project stringclasses 24
values | module stringlengths 7 49 | class stringlengths 0 32 | method stringlengths 2 37 | focal_method_txt stringlengths 43 41.5k | focal_method_lines listlengths 2 2 | in_stack bool 2
classes | globals listlengths 0 16 | type_context stringlengths 79 41.9k | has_branch bool 2
classes | total_branches int64 0 3 |
|---|---|---|---|---|---|---|---|---|---|---|---|
245 | py_backwards | py_backwards.files | get_input_output_paths | def get_input_output_paths(input_: str, output: str,
root: Optional[str]) -> Iterable[InputOutput]:
"""Get input/output paths pairs."""
if output.endswith('.py') and not input_.endswith('.py'):
raise InvalidInputOutput
if not Path(input_).exists():
raise InputDoes... | [
11,
37
] | false | [] | from typing import Iterable, Optional
from .types import InputOutput
from .exceptions import InvalidInputOutput, InputDoesntExists
def get_input_output_paths(input_: str, output: str,
root: Optional[str]) -> Iterable[InputOutput]:
"""Get input/output paths pairs."""
if output.endsw... | true | 2 | |
246 | py_backwards | py_backwards.main | main | def main() -> int:
parser = ArgumentParser(
'py-backwards',
description='Python to python compiler that allows you to use some '
'Python 3.6 features in older versions.')
parser.add_argument('-i', '--input', type=str, nargs='+', required=True,
help='in... | [
11,
53
] | false | [] | from colorama import init
from argparse import ArgumentParser
import sys
from .compiler import compile_files
from .conf import init_settings
from . import const, messages, exceptions
def main() -> int:
parser = ArgumentParser(
'py-backwards',
description='Python to python compiler that allows you... | true | 2 | |
247 | py_backwards | py_backwards.transformers.base | BaseImportRewrite | visit_Import | def visit_Import(self, node: ast.Import) -> Union[ast.Import, ast.Try]:
rewrite = self._get_matched_rewrite(node.names[0].name)
if rewrite:
return self._replace_import(node, *rewrite)
return self.generic_visit(node) | [
67,
72
] | false | [] | from abc import ABCMeta, abstractmethod
from typing import List, Tuple, Union, Optional, Iterable, Dict
from typed_ast import ast3 as ast
from ..types import CompilationTarget, TransformationResult
from ..utils.snippet import snippet, extend
class BaseImportRewrite(BaseNodeTransformer):
rewrites = []
def v... | true | 2 |
248 | py_backwards | py_backwards.transformers.base | BaseImportRewrite | visit_ImportFrom | def visit_ImportFrom(self, node: ast.ImportFrom) -> Union[ast.ImportFrom, ast.Try]:
rewrite = self._get_matched_rewrite(node.module)
if rewrite:
return self._replace_import_from_module(node, *rewrite)
names_to_replace = dict(self._get_names_to_replace(node))
if names_to_... | [
126,
135
] | false | [] | from abc import ABCMeta, abstractmethod
from typing import List, Tuple, Union, Optional, Iterable, Dict
from typed_ast import ast3 as ast
from ..types import CompilationTarget, TransformationResult
from ..utils.snippet import snippet, extend
class BaseImportRewrite(BaseNodeTransformer):
rewrites = []
def v... | true | 2 |
249 | py_backwards | py_backwards.transformers.dict_unpacking | DictUnpackingTransformer | visit_Module | def visit_Module(self, node: ast.Module) -> ast.Module:
insert_at(0, node, merge_dicts.get_body()) # type: ignore
return self.generic_visit(node) | [
66,
68
] | false | [
"Splitted",
"Pair"
] | from typing import Union, Iterable, Optional, List, Tuple
from typed_ast import ast3 as ast
from ..utils.tree import insert_at
from ..utils.snippet import snippet
from .base import BaseNodeTransformer
Splitted = List[Union[List[Tuple[ast.expr, ast.expr]], ast.expr]]
Pair = Tuple[Optional[ast.expr], ast.expr]
class Di... | false | 0 |
250 | py_backwards | py_backwards.transformers.dict_unpacking | DictUnpackingTransformer | visit_Dict | def visit_Dict(self, node: ast.Dict) -> Union[ast.Dict, ast.Call]:
if None not in node.keys:
return self.generic_visit(node) # type: ignore
self._tree_changed = True
pairs = zip(node.keys, node.values)
splitted = self._split_by_None(pairs)
prepared = self._prepa... | [
70,
78
] | false | [
"Splitted",
"Pair"
] | from typing import Union, Iterable, Optional, List, Tuple
from typed_ast import ast3 as ast
from ..utils.tree import insert_at
from ..utils.snippet import snippet
from .base import BaseNodeTransformer
Splitted = List[Union[List[Tuple[ast.expr, ast.expr]], ast.expr]]
Pair = Tuple[Optional[ast.expr], ast.expr]
class Di... | true | 2 |
251 | py_backwards | py_backwards.transformers.metaclass | MetaclassTransformer | visit_Module | def visit_Module(self, node: ast.Module) -> ast.Module:
insert_at(0, node, six_import.get_body())
return self.generic_visit(node) | [
27,
29
] | false | [] | from typed_ast import ast3 as ast
from ..utils.snippet import snippet
from ..utils.tree import insert_at
from .base import BaseNodeTransformer
class MetaclassTransformer(BaseNodeTransformer):
target = (2, 7)
dependencies = ['six']
def visit_Module(self, node: ast.Module) -> ast.Module:
insert_... | false | 0 |
252 | py_backwards | py_backwards.transformers.metaclass | MetaclassTransformer | visit_ClassDef | def visit_ClassDef(self, node: ast.ClassDef) -> ast.ClassDef:
if node.keywords:
metaclass = node.keywords[0].value
node.bases = class_bases.get_body(metaclass=metaclass, # type: ignore
bases=ast.List(elts=node.bases))
node.ke... | [
31,
39
] | false | [] | from typed_ast import ast3 as ast
from ..utils.snippet import snippet
from ..utils.tree import insert_at
from .base import BaseNodeTransformer
class MetaclassTransformer(BaseNodeTransformer):
target = (2, 7)
dependencies = ['six']
def visit_ClassDef(self, node: ast.ClassDef) -> ast.ClassDef:
i... | true | 2 |
253 | py_backwards | py_backwards.transformers.python2_future | Python2FutureTransformer | visit_Module | def visit_Module(self, node: ast.Module) -> ast.Module:
self._tree_changed = True
node.body = imports.get_body(future='__future__') + node.body # type: ignore
return self.generic_visit(node) | [
23,
26
] | false | [] | from typed_ast import ast3 as ast
from ..utils.snippet import snippet
from .base import BaseNodeTransformer
class Python2FutureTransformer(BaseNodeTransformer):
target = (2, 7)
def visit_Module(self, node: ast.Module) -> ast.Module:
self._tree_changed = True
node.body = imports.get_body(fut... | false | 0 |
254 | py_backwards | py_backwards.transformers.return_from_generator | ReturnFromGeneratorTransformer | visit_FunctionDef | def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.FunctionDef:
generator_returns = self._find_generator_returns(node)
if generator_returns:
self._tree_changed = True
for parent, return_ in generator_returns:
self._replace_return(parent, return_)
ret... | [
63,
72
] | false | [] | from typing import List, Tuple, Any
from typed_ast import ast3 as ast
from ..utils.snippet import snippet, let
from .base import BaseNodeTransformer
class ReturnFromGeneratorTransformer(BaseNodeTransformer):
target = (3, 2)
def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.FunctionDef:
gene... | true | 2 |
255 | py_backwards | py_backwards.transformers.six_moves | MovedAttribute | __init__ | def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):
self.name = name
if new_mod is None:
new_mod = name
self.new_mod = new_mod
if new_attr is None:
if old_attr is None:
new_attr = name
else:
new... | [
7,
17
] | false | [
"_moved_attributes",
"_urllib_parse_moved_attributes",
"_urllib_error_moved_attributes",
"_urllib_request_moved_attributes",
"_urllib_response_moved_attributes",
"_urllib_robotparser_moved_attributes",
"prefixed_moves"
] | from ..utils.helpers import eager
from .base import BaseImportRewrite
_moved_attributes = [
MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),
MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),
MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfals... | true | 2 |
256 | py_backwards | py_backwards.transformers.six_moves | MovedModule | __init__ | def __init__(self, name, old, new=None):
self.name = name
if new is None:
new = name
self.new = new | [
21,
25
] | false | [
"_moved_attributes",
"_urllib_parse_moved_attributes",
"_urllib_error_moved_attributes",
"_urllib_request_moved_attributes",
"_urllib_response_moved_attributes",
"_urllib_robotparser_moved_attributes",
"prefixed_moves"
] | from ..utils.helpers import eager
from .base import BaseImportRewrite
_moved_attributes = [
MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),
MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),
MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfals... | true | 2 |
257 | py_backwards | py_backwards.transformers.starred_unpacking | StarredUnpackingTransformer | visit_List | def visit_List(self, node: ast.List) -> ast.List:
if not self._has_starred(node.elts):
return self.generic_visit(node) # type: ignore
self._tree_changed = True
return self.generic_visit(self._to_sum_of_lists(node.elts)) | [
65,
71
] | false | [
"Splitted",
"ListEntry"
] | from typing import Union, Iterable, List
from typed_ast import ast3 as ast
from .base import BaseNodeTransformer
Splitted = Union[List[ast.expr], ast.Starred]
ListEntry = Union[ast.Call, ast.List]
class StarredUnpackingTransformer(BaseNodeTransformer):
target = (3, 4)
def visit_List(self, node: ast.List) ->... | true | 2 |
258 | py_backwards | py_backwards.transformers.starred_unpacking | StarredUnpackingTransformer | visit_Call | def visit_Call(self, node: ast.Call) -> ast.Call:
if not self._has_starred(node.args):
return self.generic_visit(self.generic_visit(node)) # type: ignore
self._tree_changed = True
args = self._to_sum_of_lists(node.args)
node.args = [ast.Starred(value=args)]
ret... | [
73,
81
] | false | [
"Splitted",
"ListEntry"
] | from typing import Union, Iterable, List
from typed_ast import ast3 as ast
from .base import BaseNodeTransformer
Splitted = Union[List[ast.expr], ast.Starred]
ListEntry = Union[ast.Call, ast.List]
class StarredUnpackingTransformer(BaseNodeTransformer):
target = (3, 4)
def visit_Call(self, node: ast.Call) ->... | true | 2 |
259 | py_backwards | py_backwards.transformers.super_without_arguments | SuperWithoutArgumentsTransformer | visit_Call | def visit_Call(self, node: ast.Call) -> ast.Call:
if isinstance(node.func, ast.Name) and node.func.id == 'super' and not len(node.args):
self._replace_super_args(node)
self._tree_changed = True
return self.generic_visit(node) | [
32,
37
] | false | [] | from typed_ast import ast3 as ast
from ..utils.tree import get_closest_parent_of
from ..utils.helpers import warn
from ..exceptions import NodeNotFound
from .base import BaseNodeTransformer
class SuperWithoutArgumentsTransformer(BaseNodeTransformer):
target = (2, 7)
def visit_Call(self, node: ast.Call) -> ... | true | 2 |
260 | py_backwards | py_backwards.utils.helpers | eager | def eager(fn: Callable[..., Iterable[T]]) -> Callable[..., List[T]]:
@wraps(fn)
def wrapped(*args: Any, **kwargs: Any) -> List[T]:
return list(fn(*args, **kwargs))
return wrapped | [
11,
16
] | false | [
"T"
] | from inspect import getsource
import re
import sys
from typing import Any, Callable, Iterable, List, TypeVar
from functools import wraps
from ..conf import settings
from .. import messages
T = TypeVar('T')
def eager(fn: Callable[..., Iterable[T]]) -> Callable[..., List[T]]:
@wraps(fn)
def wrapped(*args: Any, ... | false | 0 | |
261 | py_backwards | py_backwards.utils.helpers | get_source | def get_source(fn: Callable[..., Any]) -> str:
"""Returns source code of the function."""
source_lines = getsource(fn).split('\n')
padding = len(re.findall(r'^(\s*)', source_lines[0])[0])
return '\n'.join(line[padding:] for line in source_lines) | [
31,
35
] | false | [
"T"
] | from inspect import getsource
import re
import sys
from typing import Any, Callable, Iterable, List, TypeVar
from functools import wraps
from ..conf import settings
from .. import messages
T = TypeVar('T')
def get_source(fn: Callable[..., Any]) -> str:
"""Returns source code of the function."""
source_lines =... | false | 0 | |
262 | py_backwards | py_backwards.utils.helpers | debug | def debug(get_message: Callable[[], str]) -> None:
if settings.debug:
print(messages.debug(get_message()), file=sys.stderr) | [
42,
44
] | false | [
"T"
] | from inspect import getsource
import re
import sys
from typing import Any, Callable, Iterable, List, TypeVar
from functools import wraps
from ..conf import settings
from .. import messages
T = TypeVar('T')
def debug(get_message: Callable[[], str]) -> None:
if settings.debug:
print(messages.debug(get_messa... | true | 2 | |
263 | py_backwards | py_backwards.utils.snippet | extend_tree | def extend_tree(tree: ast.AST, variables: Dict[str, Variable]) -> None:
for node in find(tree, ast.Call):
if isinstance(node.func, ast.Name) and node.func.id == 'extend':
parent, index = get_non_exp_parent_and_index(tree, node)
replace_at(index, parent, variables[node.args[0].id]) | [
92,
96
] | false | [
"Variable",
"T"
] | from typing import Callable, Any, List, Dict, Iterable, Union, TypeVar
from typed_ast import ast3 as ast
from .tree import find, get_non_exp_parent_and_index, replace_at
from .helpers import eager, VariablesGenerator, get_source
Variable = Union[ast.AST, List[ast.AST], str]
T = TypeVar('T', bound=ast.AST)
def extend_... | true | 2 | |
264 | py_backwards | py_backwards.utils.snippet | VariablesReplacer | visit_ImportFrom | def visit_ImportFrom(self, node: ast.ImportFrom) -> ast.ImportFrom:
node.module = self._replace_module(node.module)
return self.generic_visit(node) | [
71,
73
] | false | [
"Variable",
"T"
] | from typing import Callable, Any, List, Dict, Iterable, Union, TypeVar
from typed_ast import ast3 as ast
from .tree import find, get_non_exp_parent_and_index, replace_at
from .helpers import eager, VariablesGenerator, get_source
Variable = Union[ast.AST, List[ast.AST], str]
T = TypeVar('T', bound=ast.AST)
class Varia... | false | 0 |
265 | py_backwards | py_backwards.utils.snippet | VariablesReplacer | visit_alias | def visit_alias(self, node: ast.alias) -> ast.alias:
node.name = self._replace_module(node.name)
node = self._replace_field_or_node(node, 'asname')
return self.generic_visit(node) | [
75,
78
] | false | [
"Variable",
"T"
] | from typing import Callable, Any, List, Dict, Iterable, Union, TypeVar
from typed_ast import ast3 as ast
from .tree import find, get_non_exp_parent_and_index, replace_at
from .helpers import eager, VariablesGenerator, get_source
Variable = Union[ast.AST, List[ast.AST], str]
T = TypeVar('T', bound=ast.AST)
class Varia... | false | 0 |
266 | py_backwards | py_backwards.utils.snippet | snippet | get_body | def get_body(self, **snippet_kwargs: Variable) -> List[ast.AST]:
"""Get AST of snippet body with replaced variables."""
source = get_source(self._fn)
tree = ast.parse(source)
variables = self._get_variables(tree, snippet_kwargs)
extend_tree(tree, variables)
VariablesR... | [
121,
128
] | false | [
"Variable",
"T"
] | from typing import Callable, Any, List, Dict, Iterable, Union, TypeVar
from typed_ast import ast3 as ast
from .tree import find, get_non_exp_parent_and_index, replace_at
from .helpers import eager, VariablesGenerator, get_source
Variable = Union[ast.AST, List[ast.AST], str]
T = TypeVar('T', bound=ast.AST)
class Varia... | false | 0 |
267 | py_backwards | py_backwards.utils.tree | get_parent | def get_parent(tree: ast.AST, node: ast.AST, rebuild: bool = False) -> ast.AST:
"""Get parrent of node in tree."""
if node not in _parents or rebuild:
_build_parents(tree)
try:
return _parents[node]
except IndexError:
raise NodeNotFound('Parent for {} not found'.format(node)) | [
14,
22
] | false | [
"_parents",
"T"
] | from weakref import WeakKeyDictionary
from typing import Tuple, Iterable, Type, TypeVar, Union, List
from typed_ast import ast3 as ast
from ..exceptions import NodeNotFound
_parents = WeakKeyDictionary()
T = TypeVar('T', bound=ast.AST)
def get_parent(tree: ast.AST, node: ast.AST, rebuild: bool = False) -> ast.AST:
... | true | 2 | |
268 | py_backwards | py_backwards.utils.tree | get_non_exp_parent_and_index | def get_non_exp_parent_and_index(tree: ast.AST, node: ast.AST) \
-> Tuple[ast.AST, int]:
"""Get non-Exp parent and index of child."""
parent = get_parent(tree, node)
while not hasattr(parent, 'body'):
node = parent
parent = get_parent(tree, parent)
return parent, parent.body.in... | [
25,
34
] | false | [
"_parents",
"T"
] | from weakref import WeakKeyDictionary
from typing import Tuple, Iterable, Type, TypeVar, Union, List
from typed_ast import ast3 as ast
from ..exceptions import NodeNotFound
_parents = WeakKeyDictionary()
T = TypeVar('T', bound=ast.AST)
def get_non_exp_parent_and_index(tree: ast.AST, node: ast.AST) \
-> Tuple[... | true | 2 | |
269 | py_backwards | py_backwards.utils.tree | find | def find(tree: ast.AST, type_: Type[T]) -> Iterable[T]:
"""Finds all nodes with type T."""
for node in ast.walk(tree):
if isinstance(node, type_):
yield node | [
40,
44
] | false | [
"_parents",
"T"
] | from weakref import WeakKeyDictionary
from typing import Tuple, Iterable, Type, TypeVar, Union, List
from typed_ast import ast3 as ast
from ..exceptions import NodeNotFound
_parents = WeakKeyDictionary()
T = TypeVar('T', bound=ast.AST)
def find(tree: ast.AST, type_: Type[T]) -> Iterable[T]:
"""Finds all nodes wit... | true | 2 | |
270 | py_backwards | py_backwards.utils.tree | insert_at | def insert_at(index: int, parent: ast.AST,
nodes: Union[ast.AST, List[ast.AST]]) -> None:
"""Inserts nodes to parents body at index."""
if not isinstance(nodes, list):
nodes = [nodes]
for child in nodes[::-1]:
parent.body.insert(index, child) | [
47,
54
] | false | [
"_parents",
"T"
] | from weakref import WeakKeyDictionary
from typing import Tuple, Iterable, Type, TypeVar, Union, List
from typed_ast import ast3 as ast
from ..exceptions import NodeNotFound
_parents = WeakKeyDictionary()
T = TypeVar('T', bound=ast.AST)
def insert_at(index: int, parent: ast.AST,
nodes: Union[ast.AST, Lis... | true | 2 | |
271 | py_backwards | py_backwards.utils.tree | replace_at | def replace_at(index: int, parent: ast.AST,
nodes: Union[ast.AST, List[ast.AST]]) -> None:
"""Replaces node in parents body at index with nodes."""
parent.body.pop(index) # type: ignore
insert_at(index, parent, nodes) | [
57,
61
] | false | [
"_parents",
"T"
] | from weakref import WeakKeyDictionary
from typing import Tuple, Iterable, Type, TypeVar, Union, List
from typed_ast import ast3 as ast
from ..exceptions import NodeNotFound
_parents = WeakKeyDictionary()
T = TypeVar('T', bound=ast.AST)
def replace_at(index: int, parent: ast.AST,
nodes: Union[ast.AST, L... | false | 0 | |
272 | py_backwards | py_backwards.utils.tree | get_closest_parent_of | def get_closest_parent_of(tree: ast.AST, node: ast.AST,
type_: Type[T]) -> T:
"""Get a closest parent of passed type."""
parent = node
while True:
parent = get_parent(tree, parent)
if isinstance(parent, type_):
return parent | [
64,
73
] | false | [
"_parents",
"T"
] | from weakref import WeakKeyDictionary
from typing import Tuple, Iterable, Type, TypeVar, Union, List
from typed_ast import ast3 as ast
from ..exceptions import NodeNotFound
_parents = WeakKeyDictionary()
T = TypeVar('T', bound=ast.AST)
def get_closest_parent_of(tree: ast.AST, node: ast.AST,
... | true | 2 | |
273 | pymonet | pymonet.box | Box | __eq__ | def __eq__(self, other: object) -> bool:
return isinstance(other, Box) and self.value == other.value | [
19,
20
] | false | [
"T",
"U"
] | from typing import TypeVar, Generic, Callable
T = TypeVar('T')
U = TypeVar('U')
class Box(Generic[T]):
def __init__(self, value: T) -> None:
"""
:param value: value to store in Box
:type value: Any
"""
self.value = value
def __eq__(self, other: object) -> bool:
... | false | 0 |
274 | pymonet | pymonet.box | Box | to_lazy | def to_lazy(self):
"""
Transform Box into Lazy with returning value function.
:returns: not folded Lazy monad with function returning previous value
:rtype: Lazy[Function(() -> A)]
"""
from pymonet.lazy import Lazy
return Lazy(lambda: self.value) | [
80,
89
] | false | [
"T",
"U"
] | from typing import TypeVar, Generic, Callable
T = TypeVar('T')
U = TypeVar('U')
class Box(Generic[T]):
def __init__(self, value: T) -> None:
"""
:param value: value to store in Box
:type value: Any
"""
self.value = value
def to_lazy(self):
"""
Transfor... | true | 2 |
275 | pymonet | pymonet.either | Either | __eq__ | def __eq__(self, other: object) -> bool:
return isinstance(other, Either) and\
self.value == other.value and\
self.is_right() == other.is_right() | [
16,
17
] | false | [
"T",
"U"
] | from typing import TypeVar, Generic, Callable, Any
T = TypeVar('T')
U = TypeVar('U')
class Either(Generic[T]):
def __init__(self, value: T) -> None:
self.value = value
def __eq__(self, other: object) -> bool:
return isinstance(other, Either) and\
self.value == other.value and\
... | false | 0 |
276 | pymonet | pymonet.either | Either | case | def case(self, error: Callable[[T], U], success: Callable[[T], U]) -> U:
"""
Take 2 functions call only one of then with either value and return her result.
:params error: function to call when Either is Left
:type error: Function(A) -> B
:params success: function to call wh... | [
21,
34
] | false | [
"T",
"U"
] | from typing import TypeVar, Generic, Callable, Any
T = TypeVar('T')
U = TypeVar('U')
class Either(Generic[T]):
def __init__(self, value: T) -> None:
self.value = value
def case(self, error: Callable[[T], U], success: Callable[[T], U]) -> U:
"""
Take 2 functions call only one of then ... | true | 2 |
277 | pymonet | pymonet.either | Either | to_lazy | def to_lazy(self):
"""
Transform Either to Try.
:returns: Lazy monad with function returning previous value
:rtype: Lazy[Function() -> A]
"""
from pymonet.lazy import Lazy
return Lazy(lambda: self.value) | [
69,
78
] | false | [
"T",
"U"
] | from typing import TypeVar, Generic, Callable, Any
T = TypeVar('T')
U = TypeVar('U')
class Either(Generic[T]):
def __init__(self, value: T) -> None:
self.value = value
def to_lazy(self):
"""
Transform Either to Try.
:returns: Lazy monad with function returning previous value... | true | 2 |
278 | pymonet | pymonet.immutable_list | ImmutableList | __eq__ | def __eq__(self, other: object) -> bool:
return isinstance(other, ImmutableList) \
and self.head == other.head\
and self.tail == other.tail\
and self.is_empty == other.is_empty | [
17,
18
] | false | [
"T",
"U"
] | from typing import TypeVar, Generic, Callable, Optional
T = TypeVar('T')
U = TypeVar('U')
class ImmutableList(Generic[T]):
def __init__(self, head: T = None, tail: 'ImmutableList[T]' = None, is_empty: bool = False) -> None:
self.head = head
self.tail = tail
self.is_empty = is_empty
d... | false | 0 |
279 | pymonet | pymonet.immutable_list | ImmutableList | __len__ | def __len__(self):
if self.head is None:
return 0
if self.tail is None:
return 1
return len(self.tail) + 1 | [
46,
53
] | false | [
"T",
"U"
] | from typing import TypeVar, Generic, Callable, Optional
T = TypeVar('T')
U = TypeVar('U')
class ImmutableList(Generic[T]):
def __init__(self, head: T = None, tail: 'ImmutableList[T]' = None, is_empty: bool = False) -> None:
self.head = head
self.tail = tail
self.is_empty = is_empty
d... | true | 2 |
280 | pymonet | pymonet.immutable_list | ImmutableList | filter | def filter(self, fn: Callable[[Optional[T]], bool]) -> 'ImmutableList[T]':
"""
Returns new ImmutableList with only this elements that passed
info argument returns True
:param fn: function to call with ImmutableList value
:type fn: Function(A) -> bool
:returns: Immuta... | [
112,
129
] | false | [
"T",
"U"
] | from typing import TypeVar, Generic, Callable, Optional
T = TypeVar('T')
U = TypeVar('U')
class ImmutableList(Generic[T]):
def __init__(self, head: T = None, tail: 'ImmutableList[T]' = None, is_empty: bool = False) -> None:
self.head = head
self.tail = tail
self.is_empty = is_empty
d... | true | 2 |
281 | pymonet | pymonet.immutable_list | ImmutableList | find | def find(self, fn: Callable[[Optional[T]], bool]) -> Optional[T]:
"""
Returns first element of ImmutableList that passed
info argument returns True
:param fn: function to call with ImmutableList value
:type fn: Function(A) -> bool
:returns: A
"""
if s... | [
131,
149
] | false | [
"T",
"U"
] | from typing import TypeVar, Generic, Callable, Optional
T = TypeVar('T')
U = TypeVar('U')
class ImmutableList(Generic[T]):
def __init__(self, head: T = None, tail: 'ImmutableList[T]' = None, is_empty: bool = False) -> None:
self.head = head
self.tail = tail
self.is_empty = is_empty
d... | true | 2 |
282 | pymonet | pymonet.immutable_list | ImmutableList | reduce | def reduce(self, fn: Callable[[U, T], U], acc: U) -> U:
"""
Method executes a reducer function
on each element of the array, resulting in a single output value.
:param fn: function to call with ImmutableList value
:type fn: Function(A, B) -> A
:returns: A
"""... | [
151,
167
] | false | [
"T",
"U"
] | from typing import TypeVar, Generic, Callable, Optional
T = TypeVar('T')
U = TypeVar('U')
class ImmutableList(Generic[T]):
def __init__(self, head: T = None, tail: 'ImmutableList[T]' = None, is_empty: bool = False) -> None:
self.head = head
self.tail = tail
self.is_empty = is_empty
d... | true | 2 |
283 | pymonet | pymonet.lazy | Lazy | __eq__ | def __eq__(self, other: object) -> bool:
"""
Two Lazy are equals where both are evaluated both have the same value and constructor functions.
"""
return (
isinstance(other, Lazy)
and self.is_evaluated == other.is_evaluated
and self.value == other.v... | [
26,
30
] | false | [
"T",
"U",
"W"
] | from typing import TypeVar, Generic, Callable
T = TypeVar('T')
U = TypeVar('U')
W = TypeVar('W')
class Lazy(Generic[T, U]):
def __init__(self, constructor_fn: Callable[[T], U]) -> None:
"""
:param constructor_fn: function to call during fold method call
:type constructor_fn: Function() ->... | false | 0 |
284 | pymonet | pymonet.lazy | Lazy | map | def map(self, mapper: Callable[[U], W]) -> 'Lazy[T, W]':
"""
Take function Function(A) -> B and returns new Lazy with mapped result of Lazy constructor function.
Both mapper end constructor will be called only during calling fold method.
:param mapper: mapper function
:type ... | [
55,
65
] | false | [
"T",
"U",
"W"
] | from typing import TypeVar, Generic, Callable
T = TypeVar('T')
U = TypeVar('U')
W = TypeVar('W')
class Lazy(Generic[T, U]):
def __init__(self, constructor_fn: Callable[[T], U]) -> None:
"""
:param constructor_fn: function to call during fold method call
:type constructor_fn: Function() ->... | true | 2 |
285 | pymonet | pymonet.lazy | Lazy | ap | def ap(self, applicative):
"""
Applies the function inside the Lazy[A] structure to another applicative type for notempty Lazy.
For empty returns copy of itself
:param applicative: applicative contains function
:type applicative: Lazy[Function(A) -> B]
:returns: new ... | [
67,
77
] | false | [
"T",
"U",
"W"
] | from typing import TypeVar, Generic, Callable
T = TypeVar('T')
U = TypeVar('U')
W = TypeVar('W')
class Lazy(Generic[T, U]):
def __init__(self, constructor_fn: Callable[[T], U]) -> None:
"""
:param constructor_fn: function to call during fold method call
:type constructor_fn: Function() ->... | true | 2 |
286 | pymonet | pymonet.lazy | Lazy | bind | def bind(self, fn: 'Callable[[U], Lazy[U, W]]') -> 'Lazy[T, W]':
"""
Take function and call constructor function passing returned value to fn function.
It's only way to call function store in Lazy
:param fn: Function(constructor_fn) -> B
:returns: result od folder function
... | [
79,
92
] | false | [
"T",
"U",
"W"
] | from typing import TypeVar, Generic, Callable
T = TypeVar('T')
U = TypeVar('U')
W = TypeVar('W')
class Lazy(Generic[T, U]):
def __init__(self, constructor_fn: Callable[[T], U]) -> None:
"""
:param constructor_fn: function to call during fold method call
:type constructor_fn: Function() ->... | false | 0 |
287 | pymonet | pymonet.lazy | Lazy | get | def get(self, *args):
"""
Evaluate function and memoize her output or return memoized value when function was evaluated.
:returns: result of function in Lazy
:rtype: A
"""
if self.is_evaluated:
return self.value
return self._compute_value(*args) | [
94,
103
] | false | [
"T",
"U",
"W"
] | from typing import TypeVar, Generic, Callable
T = TypeVar('T')
U = TypeVar('U')
W = TypeVar('W')
class Lazy(Generic[T, U]):
def __init__(self, constructor_fn: Callable[[T], U]) -> None:
"""
:param constructor_fn: function to call during fold method call
:type constructor_fn: Function() ->... | true | 2 |
288 | pymonet | pymonet.maybe | Maybe | __eq__ | def __eq__(self, other: object) -> bool:
return isinstance(other, Maybe) and \
self.is_nothing == other.is_nothing and \
(self.is_nothing or self.value == other.value) | [
18,
19
] | false | [
"T",
"U"
] | from typing import TypeVar, Generic, Callable, Union
T = TypeVar('T')
U = TypeVar('U')
class Maybe(Generic[T]):
def __init__(self, value: T, is_nothing: bool) -> None:
self.is_nothing = is_nothing
if not is_nothing:
self.value = value
def __eq__(self, other: object) -> bool:
... | false | 0 |
289 | pymonet | pymonet.maybe | Maybe | filter | def filter(self, filterer: Callable[[T], bool]) -> Union['Maybe[T]', 'Maybe[None]']:
"""
If Maybe is empty or filterer returns False return default_value, in other case
return new instance of Maybe with the same value.
:param filterer:
:type filterer: Function(A) -> Boolean
... | [
86,
98
] | false | [
"T",
"U"
] | from typing import TypeVar, Generic, Callable, Union
T = TypeVar('T')
U = TypeVar('U')
class Maybe(Generic[T]):
def __init__(self, value: T, is_nothing: bool) -> None:
self.is_nothing = is_nothing
if not is_nothing:
self.value = value
def filter(self, filterer: Callable[[T], bool... | true | 2 |
290 | pymonet | pymonet.maybe | Maybe | to_lazy | def to_lazy(self):
"""
Transform Maybe to Try.
:returns: Lazy monad with function returning previous value in other case Left with None
:rtype: Lazy[Function() -> (A | None)]
"""
from pymonet.lazy import Lazy
if self.is_nothing:
return Lazy(lambd... | [
139,
150
] | false | [
"T",
"U"
] | from typing import TypeVar, Generic, Callable, Union
T = TypeVar('T')
U = TypeVar('U')
class Maybe(Generic[T]):
def __init__(self, value: T, is_nothing: bool) -> None:
self.is_nothing = is_nothing
if not is_nothing:
self.value = value
def to_lazy(self):
"""
Transf... | true | 2 |
291 | pymonet | pymonet.monad_try | Try | __init__ | def __init__(self, value, is_success: bool) -> None:
self.value = value
self.is_success = is_success | [
9,
11
] | false | [] | from typing import Callable
class Try:
def __init__(self, value, is_success: bool) -> None:
self.value = value
self.is_success = is_success | false | 0 |
292 | pymonet | pymonet.monad_try | Try | __eq__ | def __eq__(self, other) -> bool:
return isinstance(other, type(self))\
and self.value == other.value\
and self.is_success == other.is_success | [
13,
14
] | false | [] | from typing import Callable
class Try:
def __init__(self, value, is_success: bool) -> None:
self.value = value
self.is_success = is_success
def __eq__(self, other) -> bool:
return isinstance(other, type(self))\
and self.value == other.value\
and self.is_succe... | false | 0 |
293 | pymonet | pymonet.monad_try | Try | __str__ | def __str__(self) -> str: # pragma: no cover
return 'Try[value={}, is_success={}]'.format(self.value, self.is_success) | [
18,
19
] | false | [] | from typing import Callable
class Try:
def __init__(self, value, is_success: bool) -> None:
self.value = value
self.is_success = is_success
def __str__(self) -> str: # pragma: no cover
return 'Try[value={}, is_success={}]'.format(self.value, self.is_success) | false | 0 |
294 | pymonet | pymonet.monad_try | Try | map | def map(self, mapper):
"""
Take function and applied this function with monad value and returns new monad with mapped value.
:params mapper: function to apply on monad value
:type mapper: Function(A) -> B
:returns: for successfully new Try with mapped value, othercase copy o... | [
39,
50
] | false | [] | from typing import Callable
class Try:
def __init__(self, value, is_success: bool) -> None:
self.value = value
self.is_success = is_success
def map(self, mapper):
"""
Take function and applied this function with monad value and returns new monad with mapped value.
:... | true | 2 |
295 | pymonet | pymonet.monad_try | Try | bind | def bind(self, binder):
"""
Take function and applied this function with monad value and returns function result.
:params binder: function to apply on monad value
:type binder: Function(A) -> Try[B]
:returns: for successfully result of binder, othercase copy of self
... | [
52,
63
] | false | [] | from typing import Callable
class Try:
def __init__(self, value, is_success: bool) -> None:
self.value = value
self.is_success = is_success
def bind(self, binder):
"""
Take function and applied this function with monad value and returns function result.
:params bind... | true | 2 |
296 | pymonet | pymonet.monad_try | Try | on_success | def on_success(self, success_callback):
"""
Call success_callback function with monad value when monad is successfully.
:params success_callback: function to apply with monad value.
:type success_callback: Function(A)
:returns: self
:rtype: Try[A]
"""
... | [
65,
76
] | false | [] | from typing import Callable
class Try:
def __init__(self, value, is_success: bool) -> None:
self.value = value
self.is_success = is_success
def on_success(self, success_callback):
"""
Call success_callback function with monad value when monad is successfully.
:param... | true | 2 |
297 | pymonet | pymonet.monad_try | Try | on_fail | def on_fail(self, fail_callback):
"""
Call success_callback function with monad value when monad is not successfully.
:params fail_callback: function to apply with monad value.
:type fail_callback: Function(A)
:returns: self
:rtype: Try[A]
"""
if not ... | [
78,
89
] | false | [] | from typing import Callable
class Try:
def __init__(self, value, is_success: bool) -> None:
self.value = value
self.is_success = is_success
def on_fail(self, fail_callback):
"""
Call success_callback function with monad value when monad is not successfully.
:params ... | true | 2 |
298 | pymonet | pymonet.monad_try | Try | filter | def filter(self, filterer):
"""
Take filterer function, when monad is successfully call filterer with monad value.
When filterer returns True method returns copy of monad, othercase
not successfully Try with previous value.
:params filterer: function to apply on monad value
... | [
91,
104
] | false | [] | from typing import Callable
class Try:
def __init__(self, value, is_success: bool) -> None:
self.value = value
self.is_success = is_success
def filter(self, filterer):
"""
Take filterer function, when monad is successfully call filterer with monad value.
When filtere... | true | 2 |
299 | pymonet | pymonet.monad_try | Try | get | def get(self):
"""
Return monad value.
:returns: monad value
:rtype: A
"""
return self.value | [
106,
113
] | false | [] | from typing import Callable
class Try:
def __init__(self, value, is_success: bool) -> None:
self.value = value
self.is_success = is_success
def get(self):
"""
Return monad value.
:returns: monad value
:rtype: A
"""
return self.value | false | 0 |
300 | pymonet | pymonet.monad_try | Try | get_or_else | def get_or_else(self, default_value):
"""
Return monad value when is successfully.
Othercase return default_value argument.
:params default_value: value to return when monad is not successfully.
:type default_value: B
:returns: monad value
:rtype: A | B
... | [
115,
127
] | false | [] | from typing import Callable
class Try:
def __init__(self, value, is_success: bool) -> None:
self.value = value
self.is_success = is_success
def get_or_else(self, default_value):
"""
Return monad value when is successfully.
Othercase return default_value argument.
... | true | 2 |
301 | pymonet | pymonet.semigroups | Semigroup | __init__ | def __init__(self, value):
self.value = value | [
9,
10
] | false | [] |
class Semigroup:
def __init__(self, value):
self.value = value | false | 0 |
302 | pymonet | pymonet.semigroups | Semigroup | __eq__ | def __eq__(self, other) -> bool:
return self.value == other.value | [
12,
13
] | false | [] |
class Semigroup:
def __init__(self, value):
self.value = value
def __eq__(self, other) -> bool:
return self.value == other.value | false | 0 |
303 | pymonet | pymonet.semigroups | Semigroup | fold | def fold(self, fn):
return fn(self.value) | [
15,
16
] | false | [] |
class Semigroup:
def __init__(self, value):
self.value = value
def fold(self, fn):
return fn(self.value) | false | 0 |
304 | pymonet | pymonet.semigroups | Sum | __str__ | def __str__(self) -> str: # pragma: no cover
return 'Sum[value={}]'.format(self.value) | [
30,
31
] | false | [] |
class Sum(Semigroup):
neutral_element = 0
def __str__(self) -> str: # pragma: no cover
return 'Sum[value={}]'.format(self.value) | false | 0 |
305 | pymonet | pymonet.semigroups | Sum | concat | def concat(self, semigroup: 'Sum') -> 'Sum':
"""
:param semigroup: other semigroup to concat
:type semigroup: Sum[B]
:returns: new Sum with sum of concat semigroups values
:rtype: Sum[A]
"""
return Sum(self.value + semigroup.value) | [
33,
40
] | false | [] |
class Sum(Semigroup):
neutral_element = 0
def concat(self, semigroup: 'Sum') -> 'Sum':
"""
:param semigroup: other semigroup to concat
:type semigroup: Sum[B]
:returns: new Sum with sum of concat semigroups values
:rtype: Sum[A]
"""
return Sum(self.v... | false | 0 |
306 | pymonet | pymonet.semigroups | All | __str__ | def __str__(self) -> str: # pragma: no cover
return 'All[value={}]'.format(self.value) | [
50,
51
] | false | [] |
class All(Semigroup):
neutral_element = True
def __str__(self) -> str: # pragma: no cover
return 'All[value={}]'.format(self.value) | false | 0 |
307 | pymonet | pymonet.semigroups | All | concat | def concat(self, semigroup: 'All') -> 'All':
"""
:param semigroup: other semigroup to concat
:type semigroup: All[B]
:returns: new All with last truly value or first falsy
:rtype: All[A | B]
"""
return All(self.value and semigroup.value) | [
53,
60
] | false | [] |
class All(Semigroup):
neutral_element = True
def concat(self, semigroup: 'All') -> 'All':
"""
:param semigroup: other semigroup to concat
:type semigroup: All[B]
:returns: new All with last truly value or first falsy
:rtype: All[A | B]
"""
return All... | false | 0 |
308 | pymonet | pymonet.semigroups | One | __str__ | def __str__(self) -> str: # pragma: no cover
return 'One[value={}]'.format(self.value) | [
70,
71
] | false | [] |
class One(Semigroup):
neutral_element = False
def __str__(self) -> str: # pragma: no cover
return 'One[value={}]'.format(self.value) | false | 0 |
309 | pymonet | pymonet.semigroups | One | concat | def concat(self, semigroup):
"""
:param semigroup: other semigroup to concat
:type semigroup: One[B]
:returns: new One with first truly value or last falsy
:rtype: One[A | B]
"""
return One(self.value or semigroup.value) | [
73,
80
] | false | [] |
class One(Semigroup):
neutral_element = False
def concat(self, semigroup):
"""
:param semigroup: other semigroup to concat
:type semigroup: One[B]
:returns: new One with first truly value or last falsy
:rtype: One[A | B]
"""
return One(self.value or ... | false | 0 |
310 | pymonet | pymonet.semigroups | First | __str__ | def __str__(self) -> str: # pragma: no cover
return 'Fist[value={}]'.format(self.value) | [
88,
89
] | false | [] |
class First(Semigroup):
def __str__(self) -> str: # pragma: no cover
return 'Fist[value={}]'.format(self.value) | false | 0 |
311 | pymonet | pymonet.semigroups | First | concat | def concat(self, semigroup):
"""
:param semigroup: other semigroup to concat
:type semigroup: First[B]
:returns: new First with first value
:rtype: First[A]
"""
return First(self.value) | [
91,
98
] | false | [] |
class First(Semigroup):
def concat(self, semigroup):
"""
:param semigroup: other semigroup to concat
:type semigroup: First[B]
:returns: new First with first value
:rtype: First[A]
"""
return First(self.value) | false | 0 |
312 | pymonet | pymonet.semigroups | Last | __str__ | def __str__(self) -> str: # pragma: no cover
return 'Last[value={}]'.format(self.value) | [
106,
107
] | false | [] |
class Last(Semigroup):
def __str__(self) -> str: # pragma: no cover
return 'Last[value={}]'.format(self.value) | false | 0 |
313 | pymonet | pymonet.semigroups | Last | concat | def concat(self, semigroup):
"""
:param semigroup: other semigroup to concat
:type semigroup: Last[B]
:returns: new Last with last value
:rtype: Last[A]
"""
return Last(semigroup.value) | [
109,
116
] | false | [] |
class Last(Semigroup):
def concat(self, semigroup):
"""
:param semigroup: other semigroup to concat
:type semigroup: Last[B]
:returns: new Last with last value
:rtype: Last[A]
"""
return Last(semigroup.value) | false | 0 |
314 | pymonet | pymonet.semigroups | Map | __str__ | def __str__(self) -> str: # pragma: no cover
return 'Map[value={}]'.format(self.value) | [
124,
125
] | false | [] |
class Map(Semigroup):
def __str__(self) -> str: # pragma: no cover
return 'Map[value={}]'.format(self.value) | false | 0 |
315 | pymonet | pymonet.semigroups | Map | concat | def concat(self, semigroup):
"""
:param semigroup: other semigroup to concat
:type semigroup: Map[B]
:returns: new Map with concated all values
:rtype: Map[A]
"""
return Map(
{key: value.concat(semigroup.value[key]) for key, value in self.value.ite... | [
127,
134
] | false | [] |
class Map(Semigroup):
def concat(self, semigroup):
"""
:param semigroup: other semigroup to concat
:type semigroup: Map[B]
:returns: new Map with concated all values
:rtype: Map[A]
"""
return Map(
{key: value.concat(semigroup.value[key]) for k... | true | 2 |
316 | pymonet | pymonet.semigroups | Max | __str__ | def __str__(self) -> str: # pragma: no cover
return 'Max[value={}]'.format(self.value) | [
146,
147
] | false | [] |
class Max(Semigroup):
neutral_element = -float("inf")
def __str__(self) -> str: # pragma: no cover
return 'Max[value={}]'.format(self.value) | false | 0 |
317 | pymonet | pymonet.semigroups | Max | concat | def concat(self, semigroup):
"""
:param semigroup: other semigroup to concat
:type semigroup: Max[B]
:returns: new Max with largest value
:rtype: Max[A | B]
"""
return Max(self.value if self.value > semigroup.value else semigroup.value) | [
149,
156
] | false | [] |
class Max(Semigroup):
neutral_element = -float("inf")
def concat(self, semigroup):
"""
:param semigroup: other semigroup to concat
:type semigroup: Max[B]
:returns: new Max with largest value
:rtype: Max[A | B]
"""
return Max(self.value if self.value... | false | 0 |
318 | pymonet | pymonet.semigroups | Min | __str__ | def __str__(self) -> str: # pragma: no cover
return 'Min[value={}]'.format(self.value) | [
166,
167
] | false | [] |
class Min(Semigroup):
neutral_element = float("inf")
def __str__(self) -> str: # pragma: no cover
return 'Min[value={}]'.format(self.value) | false | 0 |
319 | pymonet | pymonet.semigroups | Min | concat | def concat(self, semigroup):
"""
:param semigroup: other semigroup to concat
:type semigroup: Min[B]
:returns: new Min with smallest value
:rtype: Min[A | B]
"""
return Min(self.value if self.value <= semigroup.value else semigroup.value) | [
169,
176
] | false | [] |
class Min(Semigroup):
neutral_element = float("inf")
def concat(self, semigroup):
"""
:param semigroup: other semigroup to concat
:type semigroup: Min[B]
:returns: new Min with smallest value
:rtype: Min[A | B]
"""
return Min(self.value if self.value... | false | 0 |
320 | pymonet | pymonet.task | Task | map | def map(self, fn):
"""
Take function, store it and call with Task value during calling fork function.
Return new Task with result of called.
:param fn: mapper function
:type fn: Function(value) -> B
:returns: new Task with mapped resolve attribute
:rtype: Tas... | [
37,
53
] | false | [] |
class Task:
def __init__(self, fork):
"""
:param fork: function to call during fork
:type fork: Function(reject, resolve) -> Any
"""
self.fork = fork
def map(self, fn):
"""
Take function, store it and call with Task value during calling fork function... | true | 3 |
321 | pymonet | pymonet.task | Task | bind | def bind(self, fn):
"""
Take function, store it and call with Task value during calling fork function.
Return result of called.
:param fn: mapper function
:type fn: Function(value) -> Task[reject, mapped_value]
:returns: new Task with mapper resolve attribute
... | [
55,
71
] | false | [] |
class Task:
def __init__(self, fork):
"""
:param fork: function to call during fork
:type fork: Function(reject, resolve) -> Any
"""
self.fork = fork
def bind(self, fn):
"""
Take function, store it and call with Task value during calling fork functio... | true | 3 |
322 | pymonet | pymonet.utils | curry | def curry(x, args_count=None):
"""
In mathematics and computer science, currying is the technique of translating the evaluation of a function.
It that takes multiple arguments (or a tuple of arguments) into evaluating a sequence of functions.
each with a single argument.
"""
if args_count is Non... | [
8,
21
] | false | [
"T"
] | from functools import reduce
from typing import TypeVar, Callable, List, Tuple, Any
T = TypeVar('T')
def curry(x, args_count=None):
"""
In mathematics and computer science, currying is the technique of translating the evaluation of a function.
It that takes multiple arguments (or a tuple of arguments) int... | true | 2 | |
323 | pymonet | pymonet.utils | cond | def cond(condition_list: List[Tuple[
Callable[[T], bool],
Callable,
]]):
"""
Function for return function depended on first function argument
cond get list of two-item tuples,
first is condition_function, second is execute_function.
Returns this execute_function witch first condition_functio... | [
116,
136
] | false | [
"T"
] | from functools import reduce
from typing import TypeVar, Callable, List, Tuple, Any
T = TypeVar('T')
def cond(condition_list: List[Tuple[
Callable[[T], bool],
Callable,
]]):
"""
Function for return function depended on first function argument
cond get list of two-item tuples,
first is conditio... | true | 2 | |
324 | pymonet | pymonet.utils | memoize | def memoize(fn: Callable, key=eq) -> Callable:
"""
Create a new function that, when invoked,
caches the result of calling fn for a given argument set and returns the result.
Subsequent calls to the memoized fn with the same argument set will not result in an additional call to fn;
instead, the cache... | [
139,
164
] | false | [
"T"
] | from functools import reduce
from typing import TypeVar, Callable, List, Tuple, Any
T = TypeVar('T')
def memoize(fn: Callable, key=eq) -> Callable:
"""
Create a new function that, when invoked,
caches the result of calling fn for a given argument set and returns the result.
Subsequent calls to the mem... | true | 2 | |
325 | pymonet | pymonet.validation | Validation | __eq__ | def __eq__(self, other):
"""
Two Validations are equals when values and errors lists are equal.
"""
return (isinstance(other, Validation) and
self.errors == other.errors and
self.value == other.value) | [
7,
11
] | false | [] |
class Validation:
def __init__(self, value, errors):
self.value = value
self.errors = errors
def __eq__(self, other):
"""
Two Validations are equals when values and errors lists are equal.
"""
return (isinstance(other, Validation) and
self.er... | false | 0 |
326 | pymonet | pymonet.validation | Validation | __str__ | def __str__(self): # pragma: no cover
if self.is_success():
return 'Validation.success[{}]'.format(self.value)
return 'Validation.fail[{}, {}]'.format(self.value, self.errors) | [
15,
18
] | false | [] |
class Validation:
def __init__(self, value, errors):
self.value = value
self.errors = errors
def __str__(self): # pragma: no cover
if self.is_success():
return 'Validation.success[{}]'.format(self.value)
return 'Validation.fail[{}, {}]'.format(self.value, self.... | false | 0 |
327 | pymonet | pymonet.validation | Validation | to_maybe | def to_maybe(self):
"""
Transform Validation to Maybe.
:returns: Maybe with Validation Value when Validation has no errors, in other case empty Maybe
:rtype: Maybe[A | None]
"""
from pymonet.maybe import Maybe
if self.is_success():
return Maybe.j... | [
110,
121
] | false | [] |
class Validation:
def __init__(self, value, errors):
self.value = value
self.errors = errors
def to_maybe(self):
"""
Transform Validation to Maybe.
:returns: Maybe with Validation Value when Validation has no errors, in other case empty Maybe
:rtype: Maybe[... | true | 2 |
328 | pymonet | pymonet.validation | Validation | to_lazy | def to_lazy(self):
"""
Transform Validation to Try.
:returns: Lazy monad with function returning Validation value
:rtype: Lazy[Function() -> (A | None)]
"""
from pymonet.lazy import Lazy
return Lazy(lambda: self.value) | [
134,
143
] | false | [] |
class Validation:
def __init__(self, value, errors):
self.value = value
self.errors = errors
def to_lazy(self):
"""
Transform Validation to Try.
:returns: Lazy monad with function returning Validation value
:rtype: Lazy[Function() -> (A | None)]
"""... | true | 2 |
329 | pypara | pypara.accounting.journaling | ReadJournalEntries | __call__ | def __call__(self, period: DateRange) -> Iterable[JournalEntry[_T]]:
pass | [
178,
179
] | false | [
"__all__",
"_T",
"_debit_mapping"
] | import datetime
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, Generic, Iterable, List, Protocol, Set, TypeVar
from ..commons.numbers import Amount, Quantity, isum
from ..commons.others import Guid, makeguid
from ..commons.zeitgeist import DateRange
from .accounts import Account... | false | 0 |
330 | pypara | pypara.accounting.ledger | build_general_ledger | def build_general_ledger(
period: DateRange, journal: Iterable[JournalEntry[_T]], initial: InitialBalances
) -> GeneralLedger[_T]:
"""
Builds a general ledger.
:param period: Accounting period.
:param journal: All available journal entries.
:param initial: Opening balances for terminal accounts... | [
161,
185
] | false | [
"__all__",
"_T",
"InitialBalances"
] | import datetime
from dataclasses import dataclass, field
from decimal import Decimal
from typing import Dict, Generic, Iterable, List, Optional, Protocol, TypeVar
from ..commons.numbers import Amount, Quantity
from ..commons.zeitgeist import DateRange
from .accounts import Account
from .generic import Balance
from .jou... | true | 2 | |
331 | pypara | pypara.accounting.ledger | compile_general_ledger_program | def compile_general_ledger_program(
read_initial_balances: ReadInitialBalances,
read_journal_entries: ReadJournalEntries[_T],
) -> GeneralLedgerProgram[_T]:
"""
Consumes implementations of the algebra and returns a program which consumes opening and closing dates and produces
a general ledger.
... | [
206,
236
] | false | [
"__all__",
"_T",
"InitialBalances"
] | import datetime
from dataclasses import dataclass, field
from decimal import Decimal
from typing import Dict, Generic, Iterable, List, Optional, Protocol, TypeVar
from ..commons.numbers import Amount, Quantity
from ..commons.zeitgeist import DateRange
from .accounts import Account
from .generic import Balance
from .jou... | false | 0 | |
332 | pypara | pypara.accounting.ledger | ReadInitialBalances | __call__ | def __call__(self, period: DateRange) -> InitialBalances:
pass | [
193,
194
] | false | [
"__all__",
"_T",
"InitialBalances"
] | import datetime
from dataclasses import dataclass, field
from decimal import Decimal
from typing import Dict, Generic, Iterable, List, Optional, Protocol, TypeVar
from ..commons.numbers import Amount, Quantity
from ..commons.zeitgeist import DateRange
from .accounts import Account
from .generic import Balance
from .jou... | false | 0 |
333 | pypara | pypara.accounting.ledger | GeneralLedgerProgram | __call__ | def __call__(self, period: DateRange) -> GeneralLedger[_T]:
pass | [
202,
203
] | false | [
"__all__",
"_T",
"InitialBalances"
] | import datetime
from dataclasses import dataclass, field
from decimal import Decimal
from typing import Dict, Generic, Iterable, List, Optional, Protocol, TypeVar
from ..commons.numbers import Amount, Quantity
from ..commons.zeitgeist import DateRange
from .accounts import Account
from .generic import Balance
from .jou... | false | 0 |
334 | pypara | pypara.dcc | DCC | calculate_fraction | def calculate_fraction(self, start: Date, asof: Date, end: Date, freq: Optional[Decimal] = None) -> Decimal:
"""
Calculates the day count fraction based on the underlying methodology after performing some general checks.
"""
## Checks if dates are provided properly:
if not st... | [
207,
217
] | false | [
"__all__",
"DCFC",
"DCCRegistry"
] | import calendar
import datetime
from decimal import Decimal
from typing import Callable, Dict, Iterable, List, NamedTuple, Optional, Set, Union
from dateutil.relativedelta import relativedelta
from .commons.numbers import ONE, ZERO
from .commons.zeitgeist import Date
from .currencies import Currencies, Currency
from .m... | true | 2 |
335 | pypara | pypara.dcc | DCC | calculate_daily_fraction | def calculate_daily_fraction(self, start: Date, asof: Date, end: Date, freq: Optional[Decimal] = None) -> Decimal:
"""
Calculates daily fraction.
"""
## Get t-1 for asof:
asof_minus_1 = asof - datetime.timedelta(days=1)
## Get the yesterday's factor:
if asof_... | [
219,
236
] | false | [
"__all__",
"DCFC",
"DCCRegistry"
] | import calendar
import datetime
from decimal import Decimal
from typing import Callable, Dict, Iterable, List, NamedTuple, Optional, Set, Union
from dateutil.relativedelta import relativedelta
from .commons.numbers import ONE, ZERO
from .commons.zeitgeist import Date
from .currencies import Currencies, Currency
from .m... | true | 2 |
336 | pypara | pypara.dcc | DCC | interest | def interest(
self,
principal: Money,
rate: Decimal,
start: Date,
asof: Date,
end: Optional[Date] = None,
freq: Optional[Decimal] = None,
) -> Money:
"""
Calculates the accrued interest.
"""
return principal * rate * self.ca... | [
238,
250
] | false | [
"__all__",
"DCFC",
"DCCRegistry"
] | import calendar
import datetime
from decimal import Decimal
from typing import Callable, Dict, Iterable, List, NamedTuple, Optional, Set, Union
from dateutil.relativedelta import relativedelta
from .commons.numbers import ONE, ZERO
from .commons.zeitgeist import Date
from .currencies import Currencies, Currency
from .m... | false | 0 |
337 | pypara | pypara.dcc | DCC | coupon | def coupon(
self,
principal: Money,
rate: Decimal,
start: Date,
asof: Date,
end: Date,
freq: Union[int, Decimal],
eom: Optional[int] = None,
) -> Money:
"""
Calculates the accrued interest for the coupon payment.
This metho... | [
252,
273
] | false | [
"__all__",
"DCFC",
"DCCRegistry"
] | import calendar
import datetime
from decimal import Decimal
from typing import Callable, Dict, Iterable, List, NamedTuple, Optional, Set, Union
from dateutil.relativedelta import relativedelta
from .commons.numbers import ONE, ZERO
from .commons.zeitgeist import Date
from .currencies import Currencies, Currency
from .m... | false | 0 |
338 | pypara | pypara.dcc | DCCRegistryMachinery | register | def register(self, dcc: DCC) -> None:
"""
Attempts to register the given day count convention.
"""
## Check if the main name is ever registered before:
if self._is_registered(dcc.name):
## Yep, raise a TypeError:
raise TypeError(f"Day count convention ... | [
309,
329
] | false | [
"__all__",
"DCFC",
"DCCRegistry"
] | import calendar
import datetime
from decimal import Decimal
from typing import Callable, Dict, Iterable, List, NamedTuple, Optional, Set, Union
from dateutil.relativedelta import relativedelta
from .commons.numbers import ONE, ZERO
from .commons.zeitgeist import Date
from .currencies import Currencies, Currency
from .m... | true | 2 |
339 | pypara | pypara.dcc | DCCRegistryMachinery | find | def find(self, name: str) -> Optional[DCC]:
"""
Attempts to find the day count convention by the given name.
Note that all day count conventions are registered under stripped, uppercased names. Therefore,
the implementation will first attempt to find by given name as is. If it can n... | [
337,
345
] | false | [
"__all__",
"DCFC",
"DCCRegistry"
] | import calendar
import datetime
from decimal import Decimal
from typing import Callable, Dict, Iterable, List, NamedTuple, Optional, Set, Union
from dateutil.relativedelta import relativedelta
from .commons.numbers import ONE, ZERO
from .commons.zeitgeist import Date
from .currencies import Currencies, Currency
from .m... | false | 0 |
340 | pypara | pypara.exchange | FXRateLookupError | __init__ | def __init__(self, ccy1: Currency, ccy2: Currency, asof: Date) -> None:
"""
Initializes the foreign exchange rate lookup error.
"""
## Keep the slots:
self.ccy1 = ccy1
self.ccy2 = ccy2
self.asof = asof
## Set the message:
super().__init__(f"Fo... | [
20,
30
] | false | [
"__all__"
] | from abc import ABCMeta, abstractmethod
from decimal import Decimal
from typing import Iterable, NamedTuple, Optional, Tuple
from .commons.numbers import ONE, ZERO
from .commons.zeitgeist import Date
from .currencies import Currency
__all__ = ["FXRate", "FXRateLookupError", "FXRateService"]
class FXRateLookupError(Lo... | false | 0 |
341 | pypara | pypara.exchange | FXRate | __invert__ | def __invert__(self) -> "FXRate":
"""
Returns the inverted foreign exchange rate.
>>> import datetime
>>> from decimal import Decimal
>>> from pypara.currencies import Currencies
>>> nrate = FXRate(Currencies["EUR"], Currencies["USD"], datetime.date.today(), Decimal(... | [
80,
92
] | false | [
"__all__"
] | from abc import ABCMeta, abstractmethod
from decimal import Decimal
from typing import Iterable, NamedTuple, Optional, Tuple
from .commons.numbers import ONE, ZERO
from .commons.zeitgeist import Date
from .currencies import Currency
__all__ = ["FXRate", "FXRateLookupError", "FXRateService"]
class FXRate(NamedTuple):
... | false | 0 |
342 | pypara | pypara.exchange | FXRateService | query | @abstractmethod
def query(self, ccy1: Currency, ccy2: Currency, asof: Date, strict: bool = False) -> Optional[FXRate]:
"""
Returns the foreign exchange rate of a given currency pair as of a given date.
:param ccy1: The first currency of foreign exchange rate.
:param ccy2: The se... | [
141,
151
] | false | [
"__all__"
] | from abc import ABCMeta, abstractmethod
from decimal import Decimal
from typing import Iterable, NamedTuple, Optional, Tuple
from .commons.numbers import ONE, ZERO
from .commons.zeitgeist import Date
from .currencies import Currency
__all__ = ["FXRate", "FXRateLookupError", "FXRateService"]
class FXRateService(metacl... | false | 0 |
343 | pypara | pypara.exchange | FXRateService | queries | @abstractmethod
def queries(self, queries: Iterable[TQuery], strict: bool = False) -> Iterable[Optional[FXRate]]:
"""
Returns foreign exchange rates for a given collection of currency pairs and dates.
:param queries: An iterable of :class:`Currency`, :class:`Currency` and :class:`Tempor... | [
154,
162
] | false | [
"__all__"
] | from abc import ABCMeta, abstractmethod
from decimal import Decimal
from typing import Iterable, NamedTuple, Optional, Tuple
from .commons.numbers import ONE, ZERO
from .commons.zeitgeist import Date
from .currencies import Currency
__all__ = ["FXRate", "FXRateLookupError", "FXRateService"]
class FXRateService(metacl... | false | 0 |
344 | pypara | pypara.monetary | Money | is_equal | @abstractmethod
def is_equal(self, other: Any) -> bool:
"""
Checks the equality of two money objects.
In particular:
1. ``True`` if ``other`` is a money object **and** all slots are same.
2. ``False`` otherwise.
"""
raise NotImplementedError | [
88,
97
] | false | [
"__all__",
"Money",
"NA",
"Price"
] | from abc import abstractmethod
from decimal import Decimal, DivisionByZero, InvalidOperation
from typing import Any, NamedTuple, Optional, Union, overload
from .commons.errors import ProgrammingError
from .commons.numbers import Numeric
from .commons.zeitgeist import Date
from .currencies import Currency
from .exchange... | false | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.