code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if len(tokens) == 1: # return typedef
if self.target.startswith("3"):
return " -> " + self.wrap_typedef(tokens[0]) + ":"
else:
return ":\n" + self.wrap_comment(" type: (...) -> " + tokens[0])
else: # argument typedef
if len(t... | def typedef_handle(self, tokens) | Process Python 3 type annotations. | 4.402899 | 3.952306 | 1.114007 |
if len(tokens) == 2:
if self.target_info >= (3, 6):
return tokens[0] + ": " + self.wrap_typedef(tokens[1])
else:
return tokens[0] + " = None" + self.wrap_comment(" type: " + tokens[1])
elif len(tokens) == 3:
if self.target_info... | def typed_assign_stmt_handle(self, tokens) | Process Python 3.6 variable type annotations. | 2.627525 | 2.334849 | 1.125351 |
internal_assert(len(tokens) == 2, "invalid with statement tokens", tokens)
withs, body = tokens
if len(withs) == 1 or self.target_info >= (2, 7):
return "with " + ", ".join(withs) + body
else:
return (
"".join("with " + expr + ":\n" + open... | def with_stmt_handle(self, tokens) | Process with statements. | 5.114846 | 5.111939 | 1.000569 |
if len(tokens) == 2:
item, cases = tokens
default = None
elif len(tokens) == 3:
item, cases, default = tokens
else:
raise CoconutInternalException("invalid case tokens", tokens)
check_var = case_check_var + "_" + str(self.case_chec... | def case_stmt_handle(self, loc, tokens) | Process case blocks. | 3.515936 | 3.466821 | 1.014167 |
internal_assert(len(tokens) == 1, "invalid " + name + " tokens", tokens)
if self.strict:
raise self.make_err(CoconutStyleError, "found " + name, original, loc)
else:
return tokens[0] | def check_strict(self, name, original, loc, tokens) | Check that syntax meets --strict requirements. | 6.475248 | 6.680399 | 0.969291 |
return self.check_strict("Python-style lambda", original, loc, tokens) | def lambdef_check(self, original, loc, tokens) | Check for Python-style lambdas. | 15.394495 | 8.711255 | 1.767196 |
return self.check_strict("semicolon at end of line", original, loc, tokens) | def endline_semicolon_check(self, original, loc, tokens) | Check for semicolons at the end of lines. | 9.495561 | 6.945395 | 1.367174 |
return self.check_strict("Python-2-style unicode string", original, loc, tokens) | def u_string_check(self, original, loc, tokens) | Check for Python2-style unicode strings. | 17.477598 | 8.360016 | 2.090618 |
internal_assert(len(tokens) == 1, "invalid " + name + " tokens", tokens)
if self.target_info < get_target_info(version):
raise self.make_err(CoconutTargetError, "found Python " + ".".join(version) + " " + name, original, loc, target=version)
else:
return tokens[0... | def check_py(self, version, name, original, loc, tokens) | Check for Python-version-specific syntax. | 6.889665 | 6.508449 | 1.058572 |
internal_assert(len(tokens) == 1, "invalid name tokens", tokens)
if self.strict:
self.unused_imports.discard(tokens[0])
if tokens[0] == "exec":
return self.check_py("3", "exec function", original, loc, tokens)
elif tokens[0].startswith(reserved_prefix):
... | def name_check(self, original, loc, tokens) | Check the given base name. | 5.873231 | 5.804873 | 1.011776 |
return self.check_py("3", "nonlocal statement", original, loc, tokens) | def nonlocal_check(self, original, loc, tokens) | Check for Python 3 nonlocal statement. | 15.227624 | 8.011093 | 1.900817 |
return self.check_py("3", "starred assignment (add 'match' to front to produce universal code)", original, loc, tokens) | def star_assign_item_check(self, original, loc, tokens) | Check for Python 3 starred assignment. | 47.645123 | 28.791109 | 1.654855 |
return self.check_py("35", "star unpacking (add 'match' to front to produce universal code)", original, loc, tokens) | def star_expr_check(self, original, loc, tokens) | Check for Python 3.5 star unpacking. | 53.299789 | 28.662609 | 1.859558 |
return self.check_py("3", "keyword-only argument separator (add 'match' to front to produce universal code)", original, loc, tokens) | def star_sep_check(self, original, loc, tokens) | Check for Python 3 keyword-only arguments. | 67.674973 | 33.23595 | 2.036198 |
return self.check_py("35", "matrix multiplication", original, loc, tokens) | def matrix_at_check(self, original, loc, tokens) | Check for Python 3.5 matrix multiplication. | 23.608263 | 9.257699 | 2.550122 |
return self.check_py("35", "async for/with", original, loc, tokens) | def async_stmt_check(self, original, loc, tokens) | Check for Python 3.5 async for/with. | 19.704859 | 7.836013 | 2.514654 |
return self.check_py("36", "async comprehension", original, loc, tokens) | def async_comp_check(self, original, loc, tokens) | Check for Python 3.6 async comprehension. | 16.532436 | 9.051754 | 1.826435 |
return self.check_py("36", "format string", original, loc, tokens) | def f_string_check(self, original, loc, tokens) | Handle Python 3.6 format strings. | 20.293854 | 10.439708 | 1.94391 |
if addhash:
use_hash = self.genhash(False, inputstring)
else:
use_hash = None
return self.parse(inputstring, self.file_parser, {"nl_at_eof_check": True}, {"header": "file", "use_hash": use_hash}) | def parse_file(self, inputstring, addhash=True) | Parse file code. | 6.470198 | 6.180911 | 1.046803 |
if addhash:
use_hash = self.genhash(True, inputstring)
else:
use_hash = None
return self.parse(inputstring, self.file_parser, {"nl_at_eof_check": True}, {"header": "package", "use_hash": use_hash}) | def parse_package(self, inputstring, addhash=True) | Parse package code. | 6.568925 | 6.335604 | 1.036827 |
return self.parse(inputstring, self.file_parser, {"strip": True}, {"header": "none", "initial": "none", "final_endline": False}) | def parse_debug(self, inputstring) | Parse debug code. | 15.226397 | 14.349982 | 1.061074 |
names = []
if "paren" in match:
(match,) = match
names += get_match_names(match)
elif "var" in match:
(setvar,) = match
if setvar != wildcard:
names.append(setvar)
elif "trailer" in match:
match, trailers = match[0], match[1:]
for i in ran... | def get_match_names(match) | Gets keyword names for the given match. | 3.165102 | 3.084941 | 1.025985 |
other = Matcher(self.loc, self.check_var, self.checkdefs, self.names, self.var_index)
other.insert_check(0, "not " + self.check_var)
self.others.append(other)
return other | def duplicate(self) | Duplicates the matcher to others. | 9.88599 | 7.421852 | 1.332011 |
if position is None:
position = self.position
return self.checkdefs[position][0] | def get_checks(self, position=None) | Gets the checks at the position. | 6.266363 | 4.946741 | 1.266766 |
if position is None:
position = self.position
self.checkdefs[position][0] = checks | def set_checks(self, checks, position=None) | Sets the checks at the position. | 6.207975 | 5.103923 | 1.216314 |
if position is None:
position = self.position
return self.checkdefs[position][1] | def get_defs(self, position=None) | Gets the defs at the position. | 7.027543 | 5.35039 | 1.313464 |
if position is None:
position = self.position
self.checkdefs[position][1] = defs | def set_defs(self, defs, position=None) | Sets the defs at the position. | 8.25823 | 6.60895 | 1.249553 |
self.checks.append(check_item)
for other in self.others:
other.add_check(check_item) | def add_check(self, check_item) | Adds a check universally. | 3.686623 | 3.227798 | 1.142148 |
self.defs.append(def_item)
for other in self.others:
other.add_def(def_item) | def add_def(self, def_item) | Adds a def universally. | 3.590791 | 3.094245 | 1.160474 |
self.checks.insert(index, check_item)
for other in self.others:
other.insert_check(index, check_item) | def insert_check(self, index, check_item) | Inserts a check universally. | 3.314927 | 3.103024 | 1.068289 |
self.defs.insert(index, def_item)
for other in self.others:
other.insert_def(index, def_item) | def insert_def(self, index, def_item) | Inserts a def universally. | 3.171149 | 2.843828 | 1.115099 |
if position < 0:
position += len(self.checkdefs)
while position >= len(self.checkdefs):
self.checkdefs.append(([], []))
self.position = position | def set_position(self, position) | Sets the if-statement position. | 4.536015 | 3.72282 | 1.218435 |
others, self.others = self.others, []
try:
yield
finally:
self.others = others + self.others | def only_self(self) | Only match in self not others. | 6.883749 | 6.127028 | 1.123505 |
tempvar = match_temp_var + "_" + str(self.var_index)
self.var_index += 1
return tempvar | def get_temp_var(self) | Gets the next match_temp_var. | 6.129275 | 3.628498 | 1.689204 |
for i, match in enumerate(matches):
self.match(match, item + "[" + str(i) + "]") | def match_all_in(self, matches, item) | Matches all matches to elements of item. | 5.110255 | 4.312973 | 1.184857 |
if max_len is None:
if min_len:
self.add_check("_coconut.len(" + item + ") >= " + str(min_len))
elif min_len == max_len:
self.add_check("_coconut.len(" + item + ") == " + str(min_len))
elif not min_len:
self.add_check("_coconut.len(" +... | def check_len_in(self, min_len, max_len, item) | Checks that the length of item is in range(min_len, max_len+1). | 1.92012 | 1.906392 | 1.007201 |
self.match_in_args_kwargs(match_args, args, kwargs, allow_star_args=star_arg is not None)
if star_arg is not None:
self.match(star_arg, args + "[" + str(len(match_args)) + ":]")
self.match_in_kwargs(kwd_args, kwargs)
with self.down_a_level():
if dubstar_a... | def match_function(self, args, kwargs, match_args=(), star_arg=None, kwd_args=(), dubstar_arg=None) | Matches a pattern-matching function. | 3.76384 | 3.747402 | 1.004387 |
req_len = 0
arg_checks = {}
to_match = [] # [(move_down, match, against)]
for i, arg in enumerate(match_args):
if isinstance(arg, tuple):
(match, default) = arg
else:
match, default = arg, None
names = get_matc... | def match_in_args_kwargs(self, match_args, args, kwargs, allow_star_args=False) | Matches against args or kwargs. | 2.152522 | 2.15166 | 1.000401 |
for match, default in match_args:
names = get_match_names(match)
if names:
tempvar = self.get_temp_var()
self.add_def(
tempvar + " = "
+ "".join(
kwargs + '.pop("' + name + '") if "' ... | def match_in_kwargs(self, match_args, kwargs) | Matches against kwargs. | 6.221935 | 6.207052 | 1.002398 |
if len(tokens) == 1:
matches, rest = tokens[0], None
else:
matches, rest = tokens
self.add_check("_coconut.isinstance(" + item + ", _coconut.abc.Mapping)")
if rest is None:
self.add_check("_coconut.len(" + item + ") == " + str(len(matches)))
... | def match_dict(self, tokens, item) | Matches a dictionary. | 3.402173 | 3.376631 | 1.007564 |
if series_type == "(":
self.add_def(name + " = _coconut.tuple(" + item + ")")
elif series_type == "[":
self.add_def(name + " = _coconut.list(" + item + ")")
else:
raise CoconutInternalException("invalid series match type", series_type) | def assign_to_series(self, name, series_type, item) | Assign name to item converted to the given series_type. | 3.357688 | 3.284976 | 1.022135 |
tail = None
if len(tokens) == 2:
series_type, matches = tokens
else:
series_type, matches, tail = tokens
self.add_check("_coconut.isinstance(" + item + ", _coconut.abc.Sequence)")
if tail is None:
self.add_check("_coconut.len(" + item ... | def match_sequence(self, tokens, item) | Matches a sequence. | 3.438136 | 3.32208 | 1.034935 |
tail = None
if len(tokens) == 2:
_, matches = tokens
else:
_, matches, tail = tokens
self.add_check("_coconut.isinstance(" + item + ", _coconut.abc.Iterable)")
if tail is None:
itervar = self.get_temp_var()
self.add_def(ite... | def match_iterator(self, tokens, item) | Matches a lazy list or a chain. | 2.922915 | 2.882175 | 1.014135 |
head_matches, last_matches = None, None
if len(tokens) == 1:
middle = tokens[0]
elif len(tokens) == 2:
if isinstance(tokens[0], str):
middle, last_matches = tokens
else:
head_matches, middle = tokens
else:
... | def match_star(self, tokens, item) | Matches starred assignment. | 2.413921 | 2.392719 | 1.008861 |
front, series_type, matches = tokens
self.add_check("_coconut.isinstance(" + item + ", _coconut.abc.Sequence)")
self.add_check("_coconut.len(" + item + ") >= " + str(len(matches)))
if front != wildcard:
if len(matches):
splice = "[:" + str(-len(matche... | def match_rsequence(self, tokens, item) | Matches a reverse sequence. | 4.97731 | 4.748764 | 1.048128 |
series_type, head_matches, middle, _, last_matches = tokens
self.add_check("_coconut.isinstance(" + item + ", _coconut.abc.Sequence)")
self.add_check("_coconut.len(" + item + ") >= " + str(len(head_matches) + len(last_matches)))
if middle != wildcard:
if len(head_mat... | def match_msequence(self, tokens, item) | Matches a middle sequence. | 3.201595 | 3.079216 | 1.039744 |
prefix, name = tokens
return self.match_mstring((prefix, name, None), item, use_bytes=prefix.startswith("b")) | def match_string(self, tokens, item) | Match prefix string. | 18.669529 | 15.40471 | 1.211936 |
name, suffix = tokens
return self.match_mstring((None, name, suffix), item, use_bytes=suffix.startswith("b")) | def match_rstring(self, tokens, item) | Match suffix string. | 16.345037 | 13.03465 | 1.253968 |
prefix, name, suffix = tokens
if use_bytes is None:
if prefix.startswith("b") or suffix.startswith("b"):
if prefix.startswith("b") and suffix.startswith("b"):
use_bytes = True
else:
raise CoconutDeferredSyntaxEr... | def match_mstring(self, tokens, item, use_bytes=None) | Match prefix and suffix string. | 2.74023 | 2.690416 | 1.018515 |
match, = tokens
if match in const_vars:
self.add_check(item + " is " + match)
else:
self.add_check(item + " == " + match) | def match_const(self, tokens, item) | Matches a constant. | 6.311245 | 5.753775 | 1.096888 |
setvar, = tokens
if setvar != wildcard:
if setvar in self.names:
self.add_check(self.names[setvar] + " == " + item)
else:
self.add_def(setvar + " = " + item)
self.names[setvar] = item | def match_var(self, tokens, item) | Matches a variable. | 4.314456 | 4.240786 | 1.017372 |
match, = tokens
self.add_check("_coconut.isinstance(" + item + ", _coconut.abc.Set)")
self.add_check("_coconut.len(" + item + ") == " + str(len(match)))
for const in match:
self.add_check(const + " in " + item) | def match_set(self, tokens, item) | Matches a set. | 4.312621 | 3.813401 | 1.130912 |
if len(tokens) == 2:
data_type, matches = tokens
star_match = None
elif len(tokens) == 3:
data_type, matches, star_match = tokens
else:
raise CoconutInternalException("invalid data match tokens", tokens)
self.add_check("_coconut.is... | def match_data(self, tokens, item) | Matches a data type. | 2.543751 | 2.476544 | 1.027138 |
match, = tokens
return self.match(match, item) | def match_paren(self, tokens, item) | Matches a paren. | 17.50478 | 13.615287 | 1.285671 |
internal_assert(len(tokens) > 1 and len(tokens) % 2 == 1, "invalid trailer match tokens", tokens)
match, trailers = tokens[0], tokens[1:]
for i in range(0, len(trailers), 2):
op, arg = trailers[i], trailers[i + 1]
if op == "is":
self.add_check("_c... | def match_trailer(self, tokens, item) | Matches typedefs and as patterns. | 3.088951 | 3.008544 | 1.026726 |
for match in tokens:
self.match(match, item) | def match_and(self, tokens, item) | Matches and. | 8.34286 | 6.07115 | 1.374181 |
for x in range(1, len(tokens)):
self.duplicate().match(tokens[x], item)
with self.only_self():
self.match(tokens[0], item) | def match_or(self, tokens, item) | Matches or. | 8.292017 | 7.643113 | 1.084901 |
for flag, get_handler in self.matchers.items():
if flag in tokens:
return get_handler(self)(tokens, item)
raise CoconutInternalException("invalid pattern-matching tokens", tokens) | def match(self, tokens, item) | Performs pattern-matching processing. | 7.58026 | 6.581935 | 1.151677 |
out = ""
if self.use_sentinel:
out += sentinel_var + " = _coconut.object()\n"
closes = 0
for checks, defs in self.checkdefs:
if checks:
out += "if " + paren_join(checks, "and") + ":\n" + openindent
closes += 1
i... | def out(self) | Return pattern-matching code. | 4.247125 | 3.944779 | 1.076645 |
out = ""
if set_check_var:
out += self.check_var + " = False\n"
out += self.out()
if stmts is not None:
out += "if " + ("not " if invert else "") + self.check_var + ":" + "\n" + openindent + "".join(stmts) + closeindent
return out | def build(self, stmts=None, set_check_var=True, invert=False) | Construct code for performing the match then executing stmts. | 3.305784 | 3.212162 | 1.029146 |
return "".join(
(" " * by if line else "") + line for line in code.splitlines(True)
) | def _indent(code, by=1) | Indents every nonempty line of the given code. | 5.227536 | 4.151424 | 1.259215 |
stdout_encoding = get_encoding(sys.stdout)
inputline = str(inputline)
if rem_indents:
inputline = inputline.replace(openindent, "").replace(closeindent, "")
if strip:
inputline = inputline.strip()
return inputline.encode(stdout_encoding, encoding_errors).decode(stdout_encoding) | def clean(inputline, strip=True, rem_indents=True, encoding_errors="replace") | Clean and strip a line. | 2.500727 | 2.445839 | 1.022441 |
return clean(str(inputstr), strip, rem_indents=False, encoding_errors="backslashreplace") | def displayable(inputstr, strip=True) | Make a string displayable with minimal loss of information. | 16.988096 | 16.731855 | 1.015315 |
if DEVELOP and callable(condition):
condition = condition()
if not condition:
if message is None:
message = "assertion failed"
if item is None:
item = condition
raise CoconutInternalException(message, item, extra) | def internal_assert(condition, message=None, item=None, extra=None) | Raise InternalException if condition is False.
If condition is a function, execute it on DEVELOP only. | 4.117468 | 3.47261 | 1.185698 |
if item is not None:
message += ": " + ascii(item)
if extra is not None:
message += " (" + str(extra) + ")"
return message | def message(self, message, item, extra) | Uses arguments to create the message. | 3.553607 | 3.627169 | 0.979719 |
if message is None:
message = "parsing failed"
if ln is not None:
message += " (line " + str(ln) + ")"
if source:
if point is None:
message += "\n" + " " * taberrfmt + clean(source)
else:
part = clean(source... | def message(self, message, source, point, ln) | Creates a SyntaxError-like message. | 4.51806 | 4.31163 | 1.047877 |
args = self.args[:2] + (None, None) + self.args[4:]
err = SyntaxError(self.message(*args))
err.offset = args[2]
err.lineno = args[3]
return err | def syntax_err(self) | Creates a SyntaxError. | 4.140046 | 3.415279 | 1.212213 |
message += " (disable --strict to dismiss)"
return super(CoconutStyleError, self).message(message, source, point, ln) | def message(self, message, source, point, ln) | Creates the --strict Coconut error message. | 14.318343 | 7.392937 | 1.93676 |
if target is not None:
message += " (enable --target " + target + " to dismiss)"
return super(CoconutTargetError, self).message(message, source, point, ln) | def message(self, message, source, point, ln, target) | Creates the --target Coconut error message. | 8.267796 | 5.097516 | 1.621926 |
return (
super(CoconutInternalException, self).message(message, item, extra)
+ " " + report_this_text
) | def message(self, message, item, extra) | Creates the Coconut internal exception message. | 10.831889 | 6.22554 | 1.739912 |
success, result = parse_block_memo.get(code, (None, None))
if success is None:
try:
parsed = COMPILER.parse_block(code)
except Exception as err:
success, result = False, err
else:
success, result = True, parsed
parse_block_memo[code] = (su... | def memoized_parse_block(code) | Memoized version of parse_block. | 2.494835 | 2.485007 | 1.003955 |
kwargs["match_titles"] = True
return self.stored_nested_parse(*args, **kwargs) | def patched_nested_parse(self, *args, **kwargs) | Sets match_titles then calls stored_nested_parse. | 7.112793 | 2.612401 | 2.722703 |
self.stored_nested_parse = self.state_machine.state.nested_parse
self.state_machine.state.nested_parse = self.patched_nested_parse
try:
return super(PatchedAutoStructify, self).auto_code_block(*args, **kwargs)
finally:
self.state_machine.state.nested_pars... | def auto_code_block(self, *args, **kwargs) | Modified auto_code_block that patches nested_parse. | 2.941351 | 2.467358 | 1.192105 |
if run:
args, argv = [], []
# for coconut-run, all args beyond the source file should be wrapped in an --argv
for i in range(1, len(sys.argv)):
arg = sys.argv[i]
args.append(arg)
# if arg is source file, put everything ... | def start(self, run=False) | Process command-line arguments. | 5.266292 | 5.075898 | 1.037509 |
if args is None:
parsed_args = arguments.parse_args()
else:
parsed_args = arguments.parse_args(args)
self.exit_code = 0
with self.handling_exceptions():
self.use_args(parsed_args, interact, original_args=args)
self.exit_on_error() | def cmd(self, args=None, interact=True) | Process command-line arguments. | 3.981765 | 3.865896 | 1.029972 |
if self.comp is None:
self.comp = Compiler(*args, **kwargs)
else:
self.comp.setup(*args, **kwargs) | def setup(self, *args, **kwargs) | Set parameters for the compiler. | 4.219181 | 2.741284 | 1.539125 |
if self.exit_code:
if self.errmsg is not None:
logger.show("Exiting due to " + self.errmsg + ".")
self.errmsg = None
if self.using_jobs:
kill_children()
sys.exit(self.exit_code) | def exit_on_error(self) | Exit if exit_code is abnormal. | 5.5084 | 5.075099 | 1.085378 |
if errmsg is not None:
if self.errmsg is None:
self.errmsg = errmsg
elif errmsg not in self.errmsg:
self.errmsg += ", " + errmsg
if code is not None:
self.exit_code = max(self.exit_code, code) | def register_error(self, code=1, errmsg=None) | Update the exit code. | 2.249807 | 1.972074 | 1.140833 |
try:
if self.using_jobs:
with handling_broken_process_pool():
yield
else:
yield
except SystemExit as err:
self.register_error(err.code)
except BaseException as err:
if isinstance(err, Coc... | def handling_exceptions(self) | Perform proper exception handling. | 7.029604 | 6.852363 | 1.025866 |
path = fixpath(path)
if not isinstance(write, bool):
write = fixpath(write)
if os.path.isfile(path):
if package is None:
package = False
destpath = self.compile_file(path, write, package, *args, **kwargs)
return [destpath] ... | def compile_path(self, path, write=True, package=None, *args, **kwargs) | Compile a path and returns paths to compiled files. | 2.645403 | 2.433533 | 1.087063 |
if not isinstance(write, bool) and os.path.isfile(write):
raise CoconutException("destination path cannot point to a file when compiling a directory")
filepaths = []
for dirpath, dirnames, filenames in os.walk(directory):
if isinstance(write, bool):
... | def compile_folder(self, directory, write=True, package=True, *args, **kwargs) | Compile a directory and returns paths to compiled files. | 4.164632 | 4.03522 | 1.032071 |
set_ext = False
if write is False:
destpath = None
elif write is True:
destpath = filepath
set_ext = True
elif os.path.splitext(write)[1]:
# write is a file; it is the destination filepath
destpath = write
else:... | def compile_file(self, filepath, write=True, package=False, *args, **kwargs) | Compile a file and returns the compiled file's path. | 3.648233 | 3.537112 | 1.031416 |
with openfile(codepath, "r") as opened:
code = readfile(opened)
if destpath is not None:
destdir = os.path.dirname(destpath)
if not os.path.exists(destdir):
os.makedirs(destdir)
if package is True:
self.create_pack... | def compile(self, codepath, destpath=None, package=False, run=False, force=False, show_unchanged=True) | Compile a source Coconut file to a destination Python file. | 3.189002 | 3.122265 | 1.021375 |
if self.executor is None:
with self.handling_exceptions():
callback(getattr(self.comp, method)(*args, **kwargs))
else:
path = showpath(path)
with logger.in_path(path): # pickle the compiler in the path context
future = self.ex... | def submit_comp_job(self, path, callback, method, *args, **kwargs) | Submits a job on self.comp to be run in parallel. | 4.754072 | 4.63547 | 1.025586 |
if jobs == "sys":
self.jobs = None
else:
try:
jobs = int(jobs)
except ValueError:
jobs = -1 # will raise error below
if jobs < 0:
raise CoconutException("--jobs must be an integer >= 0 or 'sys'")
... | def set_jobs(self, jobs) | Set --jobs. | 4.440244 | 4.25408 | 1.043761 |
with self.handling_exceptions():
if self.using_jobs:
from concurrent.futures import ProcessPoolExecutor
try:
with ProcessPoolExecutor(self.jobs) as self.executor:
yield
finally:
s... | def running_jobs(self, exit_on_error=True) | Initialize multiprocessing. | 4.046546 | 3.503307 | 1.155065 |
dirpath = fixpath(dirpath)
filepath = os.path.join(dirpath, "__coconut__.py")
with openfile(filepath, "w") as opened:
writefile(opened, self.comp.getheader("__coconut__")) | def create_package(self, dirpath) | Set up a package directory. | 6.380553 | 6.085458 | 1.048492 |
if destpath is not None and os.path.isfile(destpath):
with openfile(destpath, "r") as opened:
compiled = readfile(opened)
hashash = gethash(compiled)
if hashash is not None and hashash == self.comp.genhash(package, code):
return compil... | def has_hash_of(self, destpath, code, package) | Determine if a file has the hash of the code. | 5.870496 | 6.037113 | 0.972401 |
received = None
try:
received = self.prompt.input(more)
except KeyboardInterrupt:
print()
printerr("KeyboardInterrupt")
except EOFError:
print()
self.exit_runner()
else:
if received.startswith(exit_c... | def get_input(self, more=False) | Prompt for code input. | 5.110102 | 4.74038 | 1.077994 |
self.comp.warm_up()
self.check_runner()
self.running = True | def start_running(self) | Start running the Runner. | 15.062228 | 11.344598 | 1.327701 |
logger.show("Coconut Interpreter:")
logger.show("(type 'exit()' or press Ctrl-D to end)")
self.start_running()
while self.running:
try:
code = self.get_input()
if code:
compiled = self.handle_input(code)
... | def start_prompt(self) | Start the interpreter. | 6.3202 | 5.829886 | 1.084103 |
if not self.prompt.multiline:
if not should_indent(code):
try:
return self.comp.parse_block(code)
except CoconutException:
pass
while True:
line = self.get_input(more=True)
if... | def handle_input(self, code) | Compile Coconut interpreter input. | 4.8846 | 4.110184 | 1.188414 |
self.check_runner()
if compiled is not None:
if allow_show and self.show:
print(compiled)
if path is not None: # path means header is included, and thus encoding must be removed
compiled = rem_encoding(compiled)
self.runner.ru... | def execute(self, compiled=None, path=None, use_eval=False, allow_show=True) | Execute compiled code. | 8.41466 | 7.786477 | 1.080676 |
if os.getcwd() not in sys.path:
sys.path.append(os.getcwd())
if self.runner is None:
self.runner = Runner(self.comp, exit=self.exit_runner, store=self.mypy) | def check_runner(self) | Make sure there is a runner. | 6.102458 | 5.450384 | 1.119638 |
if mypy_args is None:
self.mypy_args = None
else:
self.mypy_errs = []
self.mypy_args = list(mypy_args)
if not any(arg.startswith("--python-version") for arg in mypy_args):
self.mypy_args += [
"--python-version"... | def set_mypy_args(self, mypy_args=None) | Set MyPy arguments. | 3.601863 | 3.484382 | 1.033717 |
if self.mypy:
set_mypy_path(stub_dir)
from coconut.command.mypy import mypy_run
args = list(paths) + self.mypy_args
if code is not None:
args += ["-c", code]
for line, is_err in mypy_run(args):
if code is None o... | def run_mypy(self, paths=(), code=None) | Run MyPy with arguments. | 4.857273 | 4.696191 | 1.034301 |
install_func = partial(run_cmd, show_output=logger.verbose)
try:
install_func(["jupyter", "--version"])
except CalledProcessError:
jupyter = "ipython"
else:
jupyter = "jupyter"
# always install kernels if given no args, otherwise onl... | def start_jupyter(self, args) | Start Jupyter with the Coconut kernel. | 3.50365 | 3.387568 | 1.034267 |
from coconut.command.watch import Observer, RecompilationWatcher
source = fixpath(source)
logger.show()
logger.show_tabulated("Watching", showpath(source), "(press Ctrl-C to end)...")
def recompile(path):
path = fixpath(path)
if os.path.isfile(... | def watch(self, source, write=True, package=None, run=False, force=False) | Watch a source and recompiles on change. | 4.644525 | 4.559972 | 1.018542 |
# add Coconut built-ins
from coconut import __coconut__
newvars = {}
for var, val in vars(__coconut__).items():
if not var.startswith("__"):
newvars[var] = val
ipython.push(newvars)
# import here to avoid circular dependencies
from coconut.convenience import cmd, pa... | def load_ipython_extension(ipython) | Loads Coconut as an IPython extension. | 4.359118 | 4.208365 | 1.035822 |
if isinstance(tokens, str):
return tokens
elif isinstance(tokens, ParseResults):
# evaluate the list portion of the ParseResults
toklist, name, asList, modal = tokens.__getnewargs__()
new_toklist = [evaluate_tokens(toks) for toks in toklist]
new_tokens = ParseResults... | def evaluate_tokens(tokens) | Evaluate the given tokens in the computation graph. | 3.556597 | 3.457035 | 1.0288 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.