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 InputDoesntExists if input_.endswith('.py'): if output.endswith('.py'): yield InputOutput(Path(input_), Path(output)) else: input_path = Path(input_) if root is None: output_path = Path(output).joinpath(input_path.name) else: output_path = Path(output).joinpath(input_path.relative_to(root)) yield InputOutput(input_path, output_path) else: output_path = Path(output) input_path = Path(input_) root_path = input_path if root is None else Path(root) for child_input in input_path.glob('**/*.py'): child_output = output_path.joinpath( child_input.relative_to(root_path)) yield InputOutput(child_input, child_output)
[ 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.endswith('.py') and not input_.endswith('.py'): raise InvalidInputOutput if not Path(input_).exists(): raise InputDoesntExists if input_.endswith('.py'): if output.endswith('.py'): yield InputOutput(Path(input_), Path(output)) else: input_path = Path(input_) if root is None: output_path = Path(output).joinpath(input_path.name) else: output_path = Path(output).joinpath(input_path.relative_to(root)) yield InputOutput(input_path, output_path) else: output_path = Path(output) input_path = Path(input_) root_path = input_path if root is None else Path(root) for child_input in input_path.glob('**/*.py'): child_output = output_path.joinpath( child_input.relative_to(root_path)) yield InputOutput(child_input, child_output)
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='input file or folder') parser.add_argument('-o', '--output', type=str, required=True, help='output file or folder') parser.add_argument('-t', '--target', type=str, required=True, choices=const.TARGETS.keys(), help='target python version') parser.add_argument('-r', '--root', type=str, required=False, help='sources root') parser.add_argument('-d', '--debug', action='store_true', required=False, help='enable debug output') args = parser.parse_args() init_settings(args) try: for input_ in args.input: result = compile_files(input_, args.output, const.TARGETS[args.target], args.root) except exceptions.CompilationError as e: print(messages.syntax_error(e), file=sys.stderr) return 1 except exceptions.TransformationError as e: print(messages.transformation_error(e), file=sys.stderr) return 1 except exceptions.InputDoesntExists: print(messages.input_doesnt_exists(args.input), file=sys.stderr) return 1 except exceptions.InvalidInputOutput: print(messages.invalid_output(args.input, args.output), file=sys.stderr) return 1 except PermissionError: print(messages.permission_error(args.output), file=sys.stderr) return 1 print(messages.compilation_result(result)) return 0
[ 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 to use some ' 'Python 3.6 features in older versions.') parser.add_argument('-i', '--input', type=str, nargs='+', required=True, help='input file or folder') parser.add_argument('-o', '--output', type=str, required=True, help='output file or folder') parser.add_argument('-t', '--target', type=str, required=True, choices=const.TARGETS.keys(), help='target python version') parser.add_argument('-r', '--root', type=str, required=False, help='sources root') parser.add_argument('-d', '--debug', action='store_true', required=False, help='enable debug output') args = parser.parse_args() init_settings(args) try: for input_ in args.input: result = compile_files(input_, args.output, const.TARGETS[args.target], args.root) except exceptions.CompilationError as e: print(messages.syntax_error(e), file=sys.stderr) return 1 except exceptions.TransformationError as e: print(messages.transformation_error(e), file=sys.stderr) return 1 except exceptions.InputDoesntExists: print(messages.input_doesnt_exists(args.input), file=sys.stderr) return 1 except exceptions.InvalidInputOutput: print(messages.invalid_output(args.input, args.output), file=sys.stderr) return 1 except PermissionError: print(messages.permission_error(args.output), file=sys.stderr) return 1 print(messages.compilation_result(result)) return 0
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 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)
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_replace: return self._replace_import_from_names(node, names_to_replace) return self.generic_visit(node)
[ 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 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_replace: return self._replace_import_from_names(node, names_to_replace) return self.generic_visit(node)
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 DictUnpackingTransformer(BaseNodeTransformer): target = (3, 4) def visit_Module(self, node: ast.Module) -> ast.Module: insert_at(0, node, merge_dicts.get_body()) # type: ignore return self.generic_visit(node)
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._prepare_splitted(splitted) return self._merge_dicts(prepared)
[ 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 DictUnpackingTransformer(BaseNodeTransformer): target = (3, 4) 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._prepare_splitted(splitted) return self._merge_dicts(prepared)
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_at(0, node, six_import.get_body()) return self.generic_visit(node)
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.keywords = [] self._tree_changed = True return self.generic_visit(node)
[ 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: 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.keywords = [] self._tree_changed = True return self.generic_visit(node)
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(future='__future__') + node.body # type: ignore return self.generic_visit(node)
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_) return self.generic_visit(node)
[ 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: 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_) return self.generic_visit(node)
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_attr = old_attr self.new_attr = new_attr
[ 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", "filterfalse"), MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), MovedAttribute("intern", "__builtin__", "sys"), MovedAttribute("map", "itertools", "builtins", "imap", "map"), MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"), MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"), MovedAttribute("getstatusoutput", "commands", "subprocess"), MovedAttribute("getoutput", "commands", "subprocess"), MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("reload_module", "__builtin__", "imp", "reload"), MovedAttribute("reload_module", "__builtin__", "importlib", "reload"), MovedAttribute("reduce", "__builtin__", "functools"), MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), MovedAttribute("StringIO", "StringIO", "io"), MovedAttribute("UserDict", "UserDict", "collections"), MovedAttribute("UserList", "UserList", "collections"), MovedAttribute("UserString", "UserString", "collections"), MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), MovedModule("builtins", "__builtin__"), MovedModule("configparser", "ConfigParser"), MovedModule("copyreg", "copy_reg"), MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"), MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), MovedModule("http_cookies", "Cookie", "http.cookies"), MovedModule("html_entities", "htmlentitydefs", "html.entities"), MovedModule("html_parser", "HTMLParser", "html.parser"), MovedModule("http_client", "httplib", "http.client"), MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), MovedModule("email_mime_image", "email.MIMEImage", "email.mime.image"), MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"), MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), MovedModule("cPickle", "cPickle", "pickle"), MovedModule("queue", "Queue"), MovedModule("reprlib", "repr"), MovedModule("socketserver", "SocketServer"), MovedModule("_thread", "thread", "_thread"), MovedModule("tkinter", "Tkinter"), MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), MovedModule("tkinter_tix", "Tix", "tkinter.tix"), MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), MovedModule("tkinter_colorchooser", "tkColorChooser", "tkinter.colorchooser"), MovedModule("tkinter_commondialog", "tkCommonDialog", "tkinter.commondialog"), MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), MovedModule("tkinter_font", "tkFont", "tkinter.font"), MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", "tkinter.simpledialog"), MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), ] _urllib_parse_moved_attributes = [ MovedAttribute("ParseResult", "urlparse", "urllib.parse"), MovedAttribute("SplitResult", "urlparse", "urllib.parse"), MovedAttribute("parse_qs", "urlparse", "urllib.parse"), MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), MovedAttribute("urldefrag", "urlparse", "urllib.parse"), MovedAttribute("urljoin", "urlparse", "urllib.parse"), MovedAttribute("urlparse", "urlparse", "urllib.parse"), MovedAttribute("urlsplit", "urlparse", "urllib.parse"), MovedAttribute("urlunparse", "urlparse", "urllib.parse"), MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), MovedAttribute("quote", "urllib", "urllib.parse"), MovedAttribute("quote_plus", "urllib", "urllib.parse"), MovedAttribute("unquote", "urllib", "urllib.parse"), MovedAttribute("unquote_plus", "urllib", "urllib.parse"), MovedAttribute("unquote_to_bytes", "urllib", "urllib.parse", "unquote", "unquote_to_bytes"), MovedAttribute("urlencode", "urllib", "urllib.parse"), MovedAttribute("splitquery", "urllib", "urllib.parse"), MovedAttribute("splittag", "urllib", "urllib.parse"), MovedAttribute("splituser", "urllib", "urllib.parse"), MovedAttribute("splitvalue", "urllib", "urllib.parse"), MovedAttribute("uses_fragment", "urlparse", "urllib.parse"), MovedAttribute("uses_netloc", "urlparse", "urllib.parse"), MovedAttribute("uses_params", "urlparse", "urllib.parse"), MovedAttribute("uses_query", "urlparse", "urllib.parse"), MovedAttribute("uses_relative", "urlparse", "urllib.parse"), ] _urllib_error_moved_attributes = [ MovedAttribute("URLError", "urllib2", "urllib.error"), MovedAttribute("HTTPError", "urllib2", "urllib.error"), MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), ] _urllib_request_moved_attributes = [ MovedAttribute("urlopen", "urllib2", "urllib.request"), MovedAttribute("install_opener", "urllib2", "urllib.request"), MovedAttribute("build_opener", "urllib2", "urllib.request"), MovedAttribute("pathname2url", "urllib", "urllib.request"), MovedAttribute("url2pathname", "urllib", "urllib.request"), MovedAttribute("getproxies", "urllib", "urllib.request"), MovedAttribute("Request", "urllib2", "urllib.request"), MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), MovedAttribute("BaseHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), MovedAttribute("FileHandler", "urllib2", "urllib.request"), MovedAttribute("FTPHandler", "urllib2", "urllib.request"), MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), MovedAttribute("urlretrieve", "urllib", "urllib.request"), MovedAttribute("urlcleanup", "urllib", "urllib.request"), MovedAttribute("URLopener", "urllib", "urllib.request"), MovedAttribute("FancyURLopener", "urllib", "urllib.request"), MovedAttribute("proxy_bypass", "urllib", "urllib.request"), ] _urllib_response_moved_attributes = [ MovedAttribute("addbase", "urllib", "urllib.response"), MovedAttribute("addclosehook", "urllib", "urllib.response"), MovedAttribute("addinfo", "urllib", "urllib.response"), MovedAttribute("addinfourl", "urllib", "urllib.response"), ] _urllib_robotparser_moved_attributes = [ MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), ] prefixed_moves = [('', _moved_attributes), ('.urllib.parse', _urllib_parse_moved_attributes), ('.urllib.error', _urllib_error_moved_attributes), ('.urllib.request', _urllib_request_moved_attributes), ('.urllib.response', _urllib_response_moved_attributes), ('.urllib.robotparser', _urllib_robotparser_moved_attributes)] class MovedAttribute: 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_attr = old_attr self.new_attr = new_attr
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", "filterfalse"), MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), MovedAttribute("intern", "__builtin__", "sys"), MovedAttribute("map", "itertools", "builtins", "imap", "map"), MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"), MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"), MovedAttribute("getstatusoutput", "commands", "subprocess"), MovedAttribute("getoutput", "commands", "subprocess"), MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("reload_module", "__builtin__", "imp", "reload"), MovedAttribute("reload_module", "__builtin__", "importlib", "reload"), MovedAttribute("reduce", "__builtin__", "functools"), MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), MovedAttribute("StringIO", "StringIO", "io"), MovedAttribute("UserDict", "UserDict", "collections"), MovedAttribute("UserList", "UserList", "collections"), MovedAttribute("UserString", "UserString", "collections"), MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), MovedModule("builtins", "__builtin__"), MovedModule("configparser", "ConfigParser"), MovedModule("copyreg", "copy_reg"), MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"), MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), MovedModule("http_cookies", "Cookie", "http.cookies"), MovedModule("html_entities", "htmlentitydefs", "html.entities"), MovedModule("html_parser", "HTMLParser", "html.parser"), MovedModule("http_client", "httplib", "http.client"), MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), MovedModule("email_mime_image", "email.MIMEImage", "email.mime.image"), MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"), MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), MovedModule("cPickle", "cPickle", "pickle"), MovedModule("queue", "Queue"), MovedModule("reprlib", "repr"), MovedModule("socketserver", "SocketServer"), MovedModule("_thread", "thread", "_thread"), MovedModule("tkinter", "Tkinter"), MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), MovedModule("tkinter_tix", "Tix", "tkinter.tix"), MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), MovedModule("tkinter_colorchooser", "tkColorChooser", "tkinter.colorchooser"), MovedModule("tkinter_commondialog", "tkCommonDialog", "tkinter.commondialog"), MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), MovedModule("tkinter_font", "tkFont", "tkinter.font"), MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", "tkinter.simpledialog"), MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), ] _urllib_parse_moved_attributes = [ MovedAttribute("ParseResult", "urlparse", "urllib.parse"), MovedAttribute("SplitResult", "urlparse", "urllib.parse"), MovedAttribute("parse_qs", "urlparse", "urllib.parse"), MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), MovedAttribute("urldefrag", "urlparse", "urllib.parse"), MovedAttribute("urljoin", "urlparse", "urllib.parse"), MovedAttribute("urlparse", "urlparse", "urllib.parse"), MovedAttribute("urlsplit", "urlparse", "urllib.parse"), MovedAttribute("urlunparse", "urlparse", "urllib.parse"), MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), MovedAttribute("quote", "urllib", "urllib.parse"), MovedAttribute("quote_plus", "urllib", "urllib.parse"), MovedAttribute("unquote", "urllib", "urllib.parse"), MovedAttribute("unquote_plus", "urllib", "urllib.parse"), MovedAttribute("unquote_to_bytes", "urllib", "urllib.parse", "unquote", "unquote_to_bytes"), MovedAttribute("urlencode", "urllib", "urllib.parse"), MovedAttribute("splitquery", "urllib", "urllib.parse"), MovedAttribute("splittag", "urllib", "urllib.parse"), MovedAttribute("splituser", "urllib", "urllib.parse"), MovedAttribute("splitvalue", "urllib", "urllib.parse"), MovedAttribute("uses_fragment", "urlparse", "urllib.parse"), MovedAttribute("uses_netloc", "urlparse", "urllib.parse"), MovedAttribute("uses_params", "urlparse", "urllib.parse"), MovedAttribute("uses_query", "urlparse", "urllib.parse"), MovedAttribute("uses_relative", "urlparse", "urllib.parse"), ] _urllib_error_moved_attributes = [ MovedAttribute("URLError", "urllib2", "urllib.error"), MovedAttribute("HTTPError", "urllib2", "urllib.error"), MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), ] _urllib_request_moved_attributes = [ MovedAttribute("urlopen", "urllib2", "urllib.request"), MovedAttribute("install_opener", "urllib2", "urllib.request"), MovedAttribute("build_opener", "urllib2", "urllib.request"), MovedAttribute("pathname2url", "urllib", "urllib.request"), MovedAttribute("url2pathname", "urllib", "urllib.request"), MovedAttribute("getproxies", "urllib", "urllib.request"), MovedAttribute("Request", "urllib2", "urllib.request"), MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), MovedAttribute("BaseHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), MovedAttribute("FileHandler", "urllib2", "urllib.request"), MovedAttribute("FTPHandler", "urllib2", "urllib.request"), MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), MovedAttribute("urlretrieve", "urllib", "urllib.request"), MovedAttribute("urlcleanup", "urllib", "urllib.request"), MovedAttribute("URLopener", "urllib", "urllib.request"), MovedAttribute("FancyURLopener", "urllib", "urllib.request"), MovedAttribute("proxy_bypass", "urllib", "urllib.request"), ] _urllib_response_moved_attributes = [ MovedAttribute("addbase", "urllib", "urllib.response"), MovedAttribute("addclosehook", "urllib", "urllib.response"), MovedAttribute("addinfo", "urllib", "urllib.response"), MovedAttribute("addinfourl", "urllib", "urllib.response"), ] _urllib_robotparser_moved_attributes = [ MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), ] prefixed_moves = [('', _moved_attributes), ('.urllib.parse', _urllib_parse_moved_attributes), ('.urllib.error', _urllib_error_moved_attributes), ('.urllib.request', _urllib_request_moved_attributes), ('.urllib.response', _urllib_response_moved_attributes), ('.urllib.robotparser', _urllib_robotparser_moved_attributes)] class MovedModule: def __init__(self, name, old, new=None): self.name = name if new is None: new = name self.new = new
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) -> 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))
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)] return self.generic_visit(node)
[ 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) -> 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)] return self.generic_visit(node)
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) -> 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)
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, **kwargs: Any) -> List[T]: return list(fn(*args, **kwargs)) return wrapped
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 = getsource(fn).split('\n') padding = len(re.findall(r'^(\s*)', source_lines[0])[0]) return '\n'.join(line[padding:] for line in 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_message()), file=sys.stderr)
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_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])
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 VariablesReplacer(ast.NodeTransformer): def __init__(self, variables: Dict[str, Variable]) -> None: self._variables = variables def visit_ImportFrom(self, node: ast.ImportFrom) -> ast.ImportFrom: node.module = self._replace_module(node.module) return self.generic_visit(node)
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 VariablesReplacer(ast.NodeTransformer): def __init__(self, variables: Dict[str, Variable]) -> None: self._variables = variables 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)
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) VariablesReplacer.replace(tree, variables) return tree.body[0].body
[ 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 VariablesReplacer(ast.NodeTransformer): def __init__(self, variables: Dict[str, Variable]) -> None: self._variables = variables class snippet: def __init__(self, fn: Callable[..., None]) -> None: self._fn = fn 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) VariablesReplacer.replace(tree, variables) return tree.body[0].body
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: """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))
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.index(node)
[ 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[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.index(node)
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 with type T.""" for node in ast.walk(tree): if isinstance(node, type_): yield node
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, 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)
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, List[ast.AST]]) -> None: """Replaces node in parents body at index with nodes.""" parent.body.pop(index) # type: ignore insert_at(index, parent, nodes)
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, 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
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: return isinstance(other, Box) and self.value == other.value
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): """ 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)
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\ self.is_right() == other.is_right()
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 when Either is Right :type success: Function(A) -> B :returns: result of success handler when Eihter is Right, result of error handler when Eihter is Left :rtpye: B """ if self.is_right(): return success(self.value) return error(self.value)
[ 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 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 when Either is Right :type success: Function(A) -> B :returns: result of success handler when Eihter is Right, result of error handler when Eihter is Left :rtpye: B """ if self.is_right(): return success(self.value) return error(self.value)
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 :rtype: Lazy[Function() -> A] """ from pymonet.lazy import Lazy return Lazy(lambda: self.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 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
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 def __len__(self): if self.head is None: return 0 if self.tail is None: return 1 return len(self.tail) + 1
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: ImmutableList[A] """ if self.tail is None: if fn(self.head): return ImmutableList(self.head) return ImmutableList(is_empty=True) if fn(self.head): return ImmutableList(self.head, self.tail.filter(fn)) return self.tail.filter(fn)
[ 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 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: ImmutableList[A] """ if self.tail is None: if fn(self.head): return ImmutableList(self.head) return ImmutableList(is_empty=True) if fn(self.head): return ImmutableList(self.head, self.tail.filter(fn)) return self.tail.filter(fn)
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 self.head is None: return None if self.tail is None: return self.head if fn(self.head) else None if fn(self.head): return self.head return self.tail.find(fn)
[ 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 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 self.head is None: return None if self.tail is None: return self.head if fn(self.head) else None if fn(self.head): return self.head return self.tail.find(fn)
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 """ if self.head is None: return acc if self.tail is None: return fn(self.head, acc) return self.tail.reduce(fn, fn(acc, self.head))
[ 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 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 """ if self.head is None: return acc if self.tail is None: return fn(self.head, acc) return self.tail.reduce(fn, fn(acc, self.head))
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.value and self.constructor_fn == other.constructor_fn )
[ 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() -> A """ self.constructor_fn = constructor_fn self.is_evaluated = False self.value = None 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.value and self.constructor_fn == other.constructor_fn )
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 mapper: Function(A) -> B :returns: Lazy with mapped value :rtype: Lazy[Function() -> B)] """ return Lazy(lambda *args: mapper(self.constructor_fn(*args)))
[ 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() -> A """ self.constructor_fn = constructor_fn self.is_evaluated = False self.value = None 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 mapper: Function(A) -> B :returns: Lazy with mapped value :rtype: Lazy[Function() -> B)] """ return Lazy(lambda *args: mapper(self.constructor_fn(*args)))
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 Lazy with result of contains function :rtype: Lazy[B] """ return Lazy(lambda *args: self.constructor_fn(applicative.get(*args)))
[ 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() -> A """ self.constructor_fn = constructor_fn self.is_evaluated = False self.value = None 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 Lazy with result of contains function :rtype: Lazy[B] """ return Lazy(lambda *args: self.constructor_fn(applicative.get(*args)))
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 :rtype: B """ def lambda_fn(*args): computed_value = self._compute_value(*args) return fn(computed_value).constructor_fn return Lazy(lambda_fn)
[ 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() -> A """ self.constructor_fn = constructor_fn self.is_evaluated = False self.value = None 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 :rtype: B """ def lambda_fn(*args): computed_value = self._compute_value(*args) return fn(computed_value).constructor_fn return Lazy(lambda_fn)
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() -> A """ self.constructor_fn = constructor_fn self.is_evaluated = False self.value = None 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)
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: return isinstance(other, Maybe) and \ self.is_nothing == other.is_nothing and \ (self.is_nothing or self.value == other.value)
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 :returns: copy of self when filterer returns True, in other case empty Maybe :rtype: Maybe[A] | Maybe[None] """ if self.is_nothing or not filterer(self.value): return Maybe.nothing() return Maybe.just(self.value)
[ 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]) -> 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 :returns: copy of self when filterer returns True, in other case empty Maybe :rtype: Maybe[A] | Maybe[None] """ if self.is_nothing or not filterer(self.value): return Maybe.nothing() return Maybe.just(self.value)
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(lambda: None) return Lazy(lambda: self.value)
[ 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): """ 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(lambda: None) return Lazy(lambda: self.value)
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_success == other.is_success
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 of self :rtype: Try[B] """ if self.is_success: return Try(mapper(self.value), True) return Try(self.value, False)
[ 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. :params mapper: function to apply on monad value :type mapper: Function(A) -> B :returns: for successfully new Try with mapped value, othercase copy of self :rtype: Try[B] """ if self.is_success: return Try(mapper(self.value), True) return Try(self.value, False)
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 :rtype: Try[B] """ if self.is_success: return binder(self.value) return 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 binder: function to apply on monad value :type binder: Function(A) -> Try[B] :returns: for successfully result of binder, othercase copy of self :rtype: Try[B] """ if self.is_success: return binder(self.value) return self
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] """ if self.is_success: success_callback(self.value) return self
[ 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. :params success_callback: function to apply with monad value. :type success_callback: Function(A) :returns: self :rtype: Try[A] """ if self.is_success: success_callback(self.value) return self
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 self.is_success: fail_callback(self.value) return self
[ 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 fail_callback: function to apply with monad value. :type fail_callback: Function(A) :returns: self :rtype: Try[A] """ if not self.is_success: fail_callback(self.value) return self
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 :type filterer: Function(A) -> Boolean :returns: Try with previous value :rtype: Try[A] """ if self.is_success and filterer(self.value): return Try(self.value, True) return Try(self.value, False)
[ 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 filterer returns True method returns copy of monad, othercase not successfully Try with previous value. :params filterer: function to apply on monad value :type filterer: Function(A) -> Boolean :returns: Try with previous value :rtype: Try[A] """ if self.is_success and filterer(self.value): return Try(self.value, True) return Try(self.value, False)
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 """ if self.is_success: return self.value return default_value
[ 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. :params default_value: value to return when monad is not successfully. :type default_value: B :returns: monad value :rtype: A | B """ if self.is_success: return self.value return default_value
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.value + semigroup.value)
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(self.value and semigroup.value)
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 semigroup.value)
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.items()} )
[ 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 key, value in self.value.items()} )
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 > semigroup.value else semigroup.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 <= semigroup.value else semigroup.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: Task[Function(resolve, reject -> A | B] """ def result(reject, resolve): return self.fork( lambda arg: reject(arg), lambda arg: resolve(fn(arg)) ) return Task(result)
[ 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. Return new Task with result of called. :param fn: mapper function :type fn: Function(value) -> B :returns: new Task with mapped resolve attribute :rtype: Task[Function(resolve, reject -> A | B] """ def result(reject, resolve): return self.fork( lambda arg: reject(arg), lambda arg: resolve(fn(arg)) ) return Task(result)
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 :rtype: Task[reject, mapped_value] """ def result(reject, resolve): return self.fork( lambda arg: reject(arg), lambda arg: fn(arg).fork(reject, resolve) ) return Task(result)
[ 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 function. Return result of called. :param fn: mapper function :type fn: Function(value) -> Task[reject, mapped_value] :returns: new Task with mapper resolve attribute :rtype: Task[reject, mapped_value] """ def result(reject, resolve): return self.fork( lambda arg: reject(arg), lambda arg: fn(arg).fork(reject, resolve) ) return Task(result)
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 None: args_count = x.__code__.co_argcount def fn(*args): if len(args) == args_count: return x(*args) return curry(lambda *args1: x(*(args + args1)), args_count - len(args)) return fn
[ 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) into evaluating a sequence of functions. each with a single argument. """ if args_count is None: args_count = x.__code__.co_argcount def fn(*args): if len(args) == args_count: return x(*args) return curry(lambda *args1: x(*(args + args1)), args_count - len(args)) return fn
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_function return truly value. :param condition_list: list of two-item tuples (condition_function, execute_function) :type condition_list: List[(Function, Function)] :returns: Returns this execute_function witch first condition_function return truly value :rtype: Function """ def result(*args): for (condition_function, execute_function) in condition_list: if condition_function(*args): return execute_function(*args) return result
[ 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 condition_function, second is execute_function. Returns this execute_function witch first condition_function return truly value. :param condition_list: list of two-item tuples (condition_function, execute_function) :type condition_list: List[(Function, Function)] :returns: Returns this execute_function witch first condition_function return truly value :rtype: Function """ def result(*args): for (condition_function, execute_function) in condition_list: if condition_function(*args): return execute_function(*args) return result
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 cached result for that set of arguments will be returned. :param fn: function to invoke :type fn: Function(A) -> B :param key: function to decide if result should be taken from cache :type key: Function(A, A) -> Boolean :returns: new function invoking old one :rtype: Function(A) -> B """ cache: List[Any] = [] def memoized_fn(argument): cached_result = find(cache, lambda cacheItem: key(cacheItem[0], argument)) if cached_result is not None: return cached_result[1] fn_result = fn(argument) cache.append((argument, fn_result)) return fn_result return memoized_fn
[ 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 memoized fn with the same argument set will not result in an additional call to fn; instead, the cached result for that set of arguments will be returned. :param fn: function to invoke :type fn: Function(A) -> B :param key: function to decide if result should be taken from cache :type key: Function(A, A) -> Boolean :returns: new function invoking old one :rtype: Function(A) -> B """ cache: List[Any] = [] def memoized_fn(argument): cached_result = find(cache, lambda cacheItem: key(cacheItem[0], argument)) if cached_result is not None: return cached_result[1] fn_result = fn(argument) cache.append((argument, fn_result)) return fn_result return memoized_fn
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.errors == other.errors and self.value == other.value)
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.errors)
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.just(self.value) return Maybe.nothing()
[ 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[A | None] """ from pymonet.maybe import Maybe if self.is_success(): return Maybe.just(self.value) return Maybe.nothing()
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)] """ from pymonet.lazy import Lazy return Lazy(lambda: self.value)
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, AccountType __all__ = [ "Direction", "JournalEntry", "Posting", "ReadJournalEntries", ] _T = TypeVar("_T") _debit_mapping: Dict[Direction, Set[AccountType]] = { Direction.INC: {AccountType.ASSETS, AccountType.EQUITIES, AccountType.LIABILITIES}, Direction.DEC: {AccountType.REVENUES, AccountType.EXPENSES}, } class ReadJournalEntries(Protocol[_T]): def __call__(self, period: DateRange) -> Iterable[JournalEntry[_T]]: pass
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, if any. :return: A :py:class:`GeneralLedger` instance. """ ## Initialize ledgers buffer as per available initial balances: ledgers: Dict[Account, Ledger[_T]] = {a: Ledger(a, b) for a, b in initial.items()} ## Iterate over journal postings and populate ledgers: for posting in (p for j in journal for p in j.postings if period.since <= j.date <= period.until): ## Check if we have the ledger yet, and create if not: if posting.account not in ledgers: ledgers[posting.account] = Ledger(posting.account, Balance(period.since, Quantity(Decimal(0)))) ## Add the posting to the ledger: ledgers[posting.account].add(posting) ## Done, return general ledger. return GeneralLedger(period, ledgers)
[ 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 .journaling import JournalEntry, Posting, ReadJournalEntries __all__ = [ "GeneralLedger", "GeneralLedgerProgram", "InitialBalances", "Ledger", "LedgerEntry", "ReadInitialBalances", "build_general_ledger", "compile_general_ledger_program", ] _T = TypeVar("_T") InitialBalances = Dict[Account, Balance] 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, if any. :return: A :py:class:`GeneralLedger` instance. """ ## Initialize ledgers buffer as per available initial balances: ledgers: Dict[Account, Ledger[_T]] = {a: Ledger(a, b) for a, b in initial.items()} ## Iterate over journal postings and populate ledgers: for posting in (p for j in journal for p in j.postings if period.since <= j.date <= period.until): ## Check if we have the ledger yet, and create if not: if posting.account not in ledgers: ledgers[posting.account] = Ledger(posting.account, Balance(period.since, Quantity(Decimal(0)))) ## Add the posting to the ledger: ledgers[posting.account].add(posting) ## Done, return general ledger. return GeneralLedger(period, ledgers)
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. :param read_initial_balances: Algebra implementation which reads initial balances. :param read_journal_entries: Algebra implementation which reads journal entries. :return: A function which consumes opening and closing dates and produces a general ledger """ def _program(period: DateRange) -> GeneralLedger[_T]: """ Consumes the opening and closing dates and produces a general ledger. :param period: Accounting period. :return: A general ledger. """ ## Get initial balances as of the end of previous financial period: initial_balances = read_initial_balances(period) ## Read journal entries and post each of them: journal_entries = read_journal_entries(period) ## Build the general ledger and return: return build_general_ledger(period, journal_entries, initial_balances) ## Return the compiled program. return _program
[ 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 .journaling import JournalEntry, Posting, ReadJournalEntries __all__ = [ "GeneralLedger", "GeneralLedgerProgram", "InitialBalances", "Ledger", "LedgerEntry", "ReadInitialBalances", "build_general_ledger", "compile_general_ledger_program", ] _T = TypeVar("_T") InitialBalances = Dict[Account, Balance] 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. :param read_initial_balances: Algebra implementation which reads initial balances. :param read_journal_entries: Algebra implementation which reads journal entries. :return: A function which consumes opening and closing dates and produces a general ledger """ def _program(period: DateRange) -> GeneralLedger[_T]: """ Consumes the opening and closing dates and produces a general ledger. :param period: Accounting period. :return: A general ledger. """ ## Get initial balances as of the end of previous financial period: initial_balances = read_initial_balances(period) ## Read journal entries and post each of them: journal_entries = read_journal_entries(period) ## Build the general ledger and return: return build_general_ledger(period, journal_entries, initial_balances) ## Return the compiled program. return _program
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 .journaling import JournalEntry, Posting, ReadJournalEntries __all__ = [ "GeneralLedger", "GeneralLedgerProgram", "InitialBalances", "Ledger", "LedgerEntry", "ReadInitialBalances", "build_general_ledger", "compile_general_ledger_program", ] _T = TypeVar("_T") InitialBalances = Dict[Account, Balance] class ReadInitialBalances(Protocol): def __call__(self, period: DateRange) -> InitialBalances: pass
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 .journaling import JournalEntry, Posting, ReadJournalEntries __all__ = [ "GeneralLedger", "GeneralLedgerProgram", "InitialBalances", "Ledger", "LedgerEntry", "ReadInitialBalances", "build_general_ledger", "compile_general_ledger_program", ] _T = TypeVar("_T") InitialBalances = Dict[Account, Balance] class GeneralLedgerProgram(Protocol[_T]): def __call__(self, period: DateRange) -> GeneralLedger[_T]: pass
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 start <= asof <= end: ## Nope, return 0: return ZERO ## Cool, we can proceed with calculation based on the methodology: return self[3](start, asof, end, freq)
[ 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 .monetary import Money __all__ = ["DCC", "DCCRegistry"] DCFC = Callable[[Date, Date, Date, Optional[Decimal]], Decimal] DCCRegistry = DCCRegistryMachinery() class DCC(NamedTuple): name: str altnames: Set[str] currencies: Set[Currency] calculate_fraction_method: DCFC 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 start <= asof <= end: ## Nope, return 0: return ZERO ## Cool, we can proceed with calculation based on the methodology: return self[3](start, asof, end, freq)
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_minus_1 < start: yfact = ZERO else: yfact = self.calculate_fraction_method(start, asof_minus_1, end, freq) ## Get today's factor: tfact = self.calculate_fraction_method(start, asof, end, freq) ## Get the factor and return: return tfact - yfact
[ 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 .monetary import Money __all__ = ["DCC", "DCCRegistry"] DCFC = Callable[[Date, Date, Date, Optional[Decimal]], Decimal] DCCRegistry = DCCRegistryMachinery() class DCC(NamedTuple): name: str altnames: Set[str] currencies: Set[Currency] calculate_fraction_method: DCFC 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_minus_1 < start: yfact = ZERO else: yfact = self.calculate_fraction_method(start, asof_minus_1, end, freq) ## Get today's factor: tfact = self.calculate_fraction_method(start, asof, end, freq) ## Get the factor and return: return tfact - yfact
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.calculate_fraction(start, asof, end or asof, freq)
[ 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 .monetary import Money __all__ = ["DCC", "DCCRegistry"] DCFC = Callable[[Date, Date, Date, Optional[Decimal]], Decimal] DCCRegistry = DCCRegistryMachinery() class DCC(NamedTuple): name: str altnames: Set[str] currencies: Set[Currency] calculate_fraction_method: DCFC 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.calculate_fraction(start, asof, end or asof, freq)
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 method is primarily used for bond coupon accruals which assumes the start date to be the first of regular payment schedules. """ ## Find the previous and next payment dates: prevdate = _last_payment_date(start, asof, freq, eom) nextdate = _next_payment_date(prevdate, freq, eom) ## Calculate the interest and return: return self.interest(principal, rate, prevdate, asof, nextdate, Decimal(freq))
[ 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 .monetary import Money __all__ = ["DCC", "DCCRegistry"] DCFC = Callable[[Date, Date, Date, Optional[Decimal]], Decimal] DCCRegistry = DCCRegistryMachinery() class DCC(NamedTuple): name: str altnames: Set[str] currencies: Set[Currency] calculate_fraction_method: DCFC 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 method is primarily used for bond coupon accruals which assumes the start date to be the first of regular payment schedules. """ ## Find the previous and next payment dates: prevdate = _last_payment_date(start, asof, freq, eom) nextdate = _next_payment_date(prevdate, freq, eom) ## Calculate the interest and return: return self.interest(principal, rate, prevdate, asof, nextdate, Decimal(freq))
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 '{dcc.name}' is already registered") ## Add to the main buffer: self._buffer_main[dcc.name] = dcc ## Check if there is any registry conflict: for name in dcc.altnames: ## Check if the name is ever registered: if self._is_registered(name): ## Yep, raise a TypeError: raise TypeError(f"Day count convention '{dcc.name}' is already registered") ## Register to the alternative buffer: self._buffer_altn[name] = dcc
[ 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 .monetary import Money __all__ = ["DCC", "DCCRegistry"] DCFC = Callable[[Date, Date, Date, Optional[Decimal]], Decimal] DCCRegistry = DCCRegistryMachinery() class DCCRegistryMachinery: def __init__(self) -> None: """ Initializes the registry. """ ## Define the main registry buffer: self._buffer_main: Dict[str, DCC] = {} ## Defines the registry buffer for alternative DCC names: self._buffer_altn: Dict[str, DCC] = {} 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 '{dcc.name}' is already registered") ## Add to the main buffer: self._buffer_main[dcc.name] = dcc ## Check if there is any registry conflict: for name in dcc.altnames: ## Check if the name is ever registered: if self._is_registered(name): ## Yep, raise a TypeError: raise TypeError(f"Day count convention '{dcc.name}' is already registered") ## Register to the alternative buffer: self._buffer_altn[name] = dcc
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 not find it, it will strip and uppercase the name and try to find it as such as a last resort. """ return self._find_strict(name) or self._find_strict(name.strip().upper())
[ 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 .monetary import Money __all__ = ["DCC", "DCCRegistry"] DCFC = Callable[[Date, Date, Date, Optional[Decimal]], Decimal] DCCRegistry = DCCRegistryMachinery() class DCCRegistryMachinery: def __init__(self) -> None: """ Initializes the registry. """ ## Define the main registry buffer: self._buffer_main: Dict[str, DCC] = {} ## Defines the registry buffer for alternative DCC names: self._buffer_altn: Dict[str, DCC] = {} 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 not find it, it will strip and uppercase the name and try to find it as such as a last resort. """ return self._find_strict(name) or self._find_strict(name.strip().upper())
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"Foreign exchange rate for {ccy1}/{ccy2} not found as of {asof}")
[ 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(LookupError): 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"Foreign exchange rate for {ccy1}/{ccy2} not found as of {asof}")
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("2")) >>> rrate = FXRate(Currencies["USD"], Currencies["EUR"], datetime.date.today(), Decimal("0.5")) >>> ~nrate == rrate True """ return FXRate(self[1], self[0], self[2], self[3] ** -1)
[ 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): ccy1: Currency ccy2: Currency date: Date value: Decimal 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("2")) >>> rrate = FXRate(Currencies["USD"], Currencies["EUR"], datetime.date.today(), Decimal("0.5")) >>> ~nrate == rrate True """ return FXRate(self[1], self[0], self[2], self[3] ** -1)
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 second currency of foreign exchange rate. :param asof: Temporal dimension the foreign exchange rate is effective as of. :param strict: Indicates if we should raise a lookup error if that the foreign exchange rate can not be found. :return: The foreign exhange rate as a :class:`Decimal` instance or None. """ pass
[ 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(metaclass=ABCMeta): default: Optional["FXRateService"] = None TQuery = Tuple[Currency, Currency, Date] @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 second currency of foreign exchange rate. :param asof: Temporal dimension the foreign exchange rate is effective as of. :param strict: Indicates if we should raise a lookup error if that the foreign exchange rate can not be found. :return: The foreign exhange rate as a :class:`Decimal` instance or None. """ pass
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:`Temporal` tuples. :param strict: Indicates if we should raise a lookup error if that the foreign exchange rate can not be found. :return: An iterable of rates. """ pass
[ 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(metaclass=ABCMeta): default: Optional["FXRateService"] = None TQuery = Tuple[Currency, Currency, Date] @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:`Temporal` tuples. :param strict: Indicates if we should raise a lookup error if that the foreign exchange rate can not be found. :return: An iterable of rates. """ pass
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 import FXRateLookupError, FXRateService __all__ = [ "IncompatibleCurrencyError", "MonetaryOperationException", "Money", "NoMoney", "NoPrice", "NoneMoney", "NonePrice", "Price", "SomeMoney", "SomePrice", ] Money.NA = NoMoney = NoneMoney() Price.NA = NoPrice = NonePrice() Price.NA = NoPrice = NonePrice() class Money: __slots__ = () NA: "Money" ccy: Currency qty: Decimal dov: Date defined: bool undefined: bool @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
false
0