signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def main():
Command().start()<EOL>
Starts coconut.
f11262:m1
def main_run():
Command().start(run=True)<EOL>
Starts coconut-run.
f11262:m2
def openfile(filename, opentype="<STR_LIT>"):
return open(filename, opentype, encoding=default_encoding)<EOL>
Open a file using default_encoding.
f11263:m0
def writefile(openedfile, newcontents):
openedfile.seek(<NUM_LIT:0>)<EOL>openedfile.truncate()<EOL>openedfile.write(newcontents)<EOL>
Set the contents of a file.
f11263:m1
def readfile(openedfile):
openedfile.seek(<NUM_LIT:0>)<EOL>return str(openedfile.read())<EOL>
Read the contents of a file.
f11263:m2
def launch_tutorial():
import webbrowser <EOL>webbrowser.open(tutorial_url, <NUM_LIT:2>)<EOL>
Open the Coconut tutorial.
f11263:m3
def launch_documentation():
import webbrowser <EOL>webbrowser.open(documentation_url, <NUM_LIT:2>)<EOL>
Open the Coconut documentation.
f11263:m4
def showpath(path):
if logger.verbose:<EOL><INDENT>return os.path.abspath(path)<EOL><DEDENT>else:<EOL><INDENT>path = os.path.relpath(path)<EOL>if path.startswith(os.curdir + os.sep):<EOL><INDENT>path = path[len(os.curdir + os.sep):]<EOL><DEDENT>return path<EOL><DEDENT>
Format a path for displaying.
f11263:m5
def is_special_dir(dirname):
return dirname == os.curdir or dirname == os.pardir<EOL>
Determine if a directory name is a special directory.
f11263:m6
def rem_encoding(code):
old_lines = code.splitlines()<EOL>new_lines = []<EOL>for i in range(min(<NUM_LIT:2>, len(old_lines))):<EOL><INDENT>line = old_lines[i]<EOL>if not (line.lstrip().startswith("<STR_LIT:#>") and "<STR_LIT>" in line):<EOL><INDENT>new_lines.append(line)<EOL><DEDENT><DEDENT>new_lines += old_lines[<NUM_LIT:2>:]<EOL>return "<ST...
Remove encoding declarations from compiled code so it can be passed to exec.
f11263:m7
def exec_func(code, glob_vars, loc_vars=None):
if loc_vars is None:<EOL><INDENT>exec(code, glob_vars)<EOL><DEDENT>else:<EOL><INDENT>exec(code, glob_vars, loc_vars)<EOL><DEDENT>
Wrapper around exec.
f11263:m8
def interpret(code, in_vars):
try:<EOL><INDENT>result = eval(code, in_vars)<EOL><DEDENT>except SyntaxError:<EOL><INDENT>pass <EOL><DEDENT>else:<EOL><INDENT>if result is not None:<EOL><INDENT>print(ascii(result))<EOL><DEDENT>return <EOL><DEDENT>exec_func(code, in_vars)<EOL>
Try to evaluate the given code, otherwise execute it.
f11263:m9
@contextmanager<EOL>def handling_broken_process_pool():
if sys.version_info < (<NUM_LIT:3>, <NUM_LIT:3>):<EOL><INDENT>yield<EOL><DEDENT>else:<EOL><INDENT>from concurrent.futures.process import BrokenProcessPool<EOL>try:<EOL><INDENT>yield<EOL><DEDENT>except BrokenProcessPool:<EOL><INDENT>raise KeyboardInterrupt()<EOL><DEDENT><DEDENT>
Handle BrokenProcessPool error.
f11263:m10
def kill_children():
try:<EOL><INDENT>import psutil<EOL><DEDENT>except ImportError:<EOL><INDENT>logger.warn(<EOL>"<STR_LIT>",<EOL>extra="<STR_LIT>",<EOL>)<EOL><DEDENT>else:<EOL><INDENT>master = psutil.Process()<EOL>children = master.children(recursive=True)<EOL>while children:<EOL><INDENT>for child in children:<EOL><INDENT>try:<EOL><INDENT...
Terminate all child processes.
f11263:m11
def splitname(path):
dirpath, filename = os.path.split(path)<EOL>name, exts = filename.split(os.extsep, <NUM_LIT:1>)<EOL>return dirpath, name, exts<EOL>
Split a path into a directory, name, and extensions.
f11263:m12
def run_file(path):
if PY26:<EOL><INDENT>dirpath, name, _ = splitname(path)<EOL>found = imp.find_module(name, [dirpath])<EOL>module = imp.load_module("<STR_LIT:__main__>", *found)<EOL>return vars(module)<EOL><DEDENT>else:<EOL><INDENT>return runpy.run_path(path, run_name="<STR_LIT:__main__>")<EOL><DEDENT>
Run a module from a path and return its variables.
f11263:m13
def call_output(cmd, stdin=None, encoding_errors="<STR_LIT:replace>", **kwargs):
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)<EOL>stdout, stderr, retcode = [], [], None<EOL>while retcode is None:<EOL><INDENT>if stdin is not None:<EOL><INDENT>logger.log_prefix("<STR_LIT>", stdin.rstrip())<EOL><DEDENT>raw_out, raw_err = p.communicate(stdin)<EOL>stdin = None<EOL>...
Run command and read output.
f11263:m14
def run_cmd(cmd, show_output=True, raise_errs=True, **kwargs):
internal_assert(cmd and isinstance(cmd, list), "<STR_LIT>")<EOL>try:<EOL><INDENT>from shutil import which<EOL><DEDENT>except ImportError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>cmd[<NUM_LIT:0>] = which(cmd[<NUM_LIT:0>]) or cmd[<NUM_LIT:0>]<EOL><DEDENT>logger.log_cmd(cmd)<EOL>try:<EOL><INDENT>if show_output and ...
Run a console command. When show_output=True, prints output and returns exit code, otherwise returns output. When raise_errs=True, raises a subprocess.CalledProcessError if the command fails.
f11263:m15
def set_mypy_path(mypy_path):
original = os.environ.get(mypy_path_env_var)<EOL>if original is None:<EOL><INDENT>new_mypy_path = mypy_path<EOL><DEDENT>elif not original.startswith(mypy_path):<EOL><INDENT>new_mypy_path = mypy_path + os.pathsep + original<EOL><DEDENT>else:<EOL><INDENT>new_mypy_path = None<EOL><DEDENT>if new_mypy_path is not None:<EOL>...
Prepend to MYPYPATH.
f11263:m16
def stdin_readable():
if not WINDOWS:<EOL><INDENT>try:<EOL><INDENT>return bool(select([sys.stdin], [], [], <NUM_LIT:0>)[<NUM_LIT:0>])<EOL><DEDENT>except Exception:<EOL><INDENT>logger.log_exc()<EOL><DEDENT><DEDENT>try:<EOL><INDENT>return not sys.stdin.isatty()<EOL><DEDENT>except Exception:<EOL><INDENT>logger.log_exc()<EOL><DEDENT>return Fals...
Determine whether stdin has any data to read.
f11263:m17
def set_recursion_limit(limit):
if limit < minimum_recursion_limit:<EOL><INDENT>raise CoconutException("<STR_LIT>" + str(minimum_recursion_limit))<EOL><DEDENT>sys.setrecursionlimit(limit)<EOL>
Set the Python recursion limit.
f11263:m18
def canparse(argparser, args):
old_error_method = argparser.error<EOL>argparser.error = _raise_ValueError<EOL>try:<EOL><INDENT>argparser.parse_args(args)<EOL><DEDENT>except ValueError:<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>return True<EOL><DEDENT>finally:<EOL><INDENT>argparser.error = old_error_method<EOL><DEDENT>
Determines if argparser can parse args.
f11263:m20
def __init__(self):
if prompt_toolkit is not None:<EOL><INDENT>self.set_style(os.environ.get(style_env_var, default_style))<EOL>self.set_history_file(os.environ.get(histfile_env_var, default_histfile))<EOL><DEDENT>
Set up the prompt.
f11263:c0:m0
def set_style(self, style):
if style == "<STR_LIT:none>":<EOL><INDENT>self.style = None<EOL><DEDENT>elif prompt_toolkit is None:<EOL><INDENT>raise CoconutException("<STR_LIT>")<EOL><DEDENT>elif style == "<STR_LIT:list>":<EOL><INDENT>print("<STR_LIT>" + "<STR_LIT:U+002CU+0020>".join(pygments.styles.get_all_styles()))<EOL>sys.exit(<NUM_LIT:0>)<EOL>...
Set pygments syntax highlighting style.
f11263:c0:m1
def set_history_file(self, path):
if path:<EOL><INDENT>self.history = prompt_toolkit.history.FileHistory(fixpath(path))<EOL><DEDENT>else:<EOL><INDENT>self.history = prompt_toolkit.history.InMemoryHistory()<EOL><DEDENT>
Set path to history file. "" produces no file.
f11263:c0:m2
def input(self, more=False):
sys.stdout.flush()<EOL>if more:<EOL><INDENT>msg = more_prompt<EOL><DEDENT>else:<EOL><INDENT>msg = main_prompt<EOL><DEDENT>if self.style is not None:<EOL><INDENT>internal_assert(prompt_toolkit is not None, "<STR_LIT>", self.style)<EOL>try:<EOL><INDENT>return self.prompt(msg)<EOL><DEDENT>except EOFError:<EOL><INDENT>rais...
Prompt for code input.
f11263:c0:m3
def prompt(self, msg):
try:<EOL><INDENT>prompt = prompt_toolkit.PromptSession(history=self.history).prompt<EOL><DEDENT>except AttributeError:<EOL><INDENT>prompt = partial(prompt_toolkit.prompt, history=self.history)<EOL><DEDENT>return prompt(<EOL>msg,<EOL>multiline=self.multiline,<EOL>vi_mode=self.vi_mode,<EOL>wrap_lines=self.wrap_lines,<EOL...
Get input using prompt_toolkit.
f11263:c0:m4
def __init__(self, comp=None, exit=sys.exit, store=False, path=None):
<EOL>import coconut.convenience <EOL>self.exit = exit<EOL>self.vars = self.build_vars(path)<EOL>self.stored = [] if store else None<EOL>if comp is not None:<EOL><INDENT>self.store(comp.getheader("<STR_LIT>"))<EOL>self.run(comp.getheader("<STR_LIT:code>"), store=False)<EOL>self.fix_pickle()<EOL><DEDENT>
Create the executor.
f11263:c1:m0
@staticmethod<EOL><INDENT>def build_vars(path=None):<DEDENT>
init_vars = {<EOL>"<STR_LIT>": "<STR_LIT:__main__>",<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT>": reload,<EOL>}<EOL>if path is not None:<EOL><INDENT>init_vars["<STR_LIT>"] = fixpath(path)<EOL><DEDENT>for var in reserved_vars:<EOL><INDENT>init_vars[var] = None<EOL><DEDENT>return init_vars<EOL>
Build initial vars.
f11263:c1:m1
def store(self, line):
if self.stored is not None:<EOL><INDENT>self.stored.append(line)<EOL><DEDENT>
Store a line.
f11263:c1:m2
def fix_pickle(self):
from coconut import __coconut__ <EOL>for var in self.vars:<EOL><INDENT>if not var.startswith("<STR_LIT>") and var in dir(__coconut__):<EOL><INDENT>self.vars[var] = getattr(__coconut__, var)<EOL><DEDENT><DEDENT>
Fix pickling of Coconut header objects.
f11263:c1:m3
@contextmanager<EOL><INDENT>def handling_errors(self, all_errors_exit=False):<DEDENT>
try:<EOL><INDENT>yield<EOL><DEDENT>except SystemExit as err:<EOL><INDENT>self.exit(err.code)<EOL><DEDENT>except BaseException:<EOL><INDENT>etype, value, tb = sys.exc_info()<EOL>for _ in range(num_added_tb_layers):<EOL><INDENT>if tb is None:<EOL><INDENT>break<EOL><DEDENT>tb = tb.tb_next<EOL><DEDENT>traceback.print_excep...
Handle execution errors.
f11263:c1:m4
def update_vars(self, global_vars):
global_vars.update(self.vars)<EOL>
Add Coconut built-ins to given vars.
f11263:c1:m5
def run(self, code, use_eval=None, path=None, all_errors_exit=False, store=True):
if use_eval is None:<EOL><INDENT>run_func = interpret<EOL><DEDENT>elif use_eval is True:<EOL><INDENT>run_func = eval<EOL><DEDENT>else:<EOL><INDENT>run_func = exec_func<EOL><DEDENT>with self.handling_errors(all_errors_exit):<EOL><INDENT>if path is None:<EOL><INDENT>result = run_func(code, self.vars)<EOL><DEDENT>else:<EO...
Execute Python code.
f11263:c1:m6
def run_file(self, path, all_errors_exit=True):
path = fixpath(path)<EOL>with self.handling_errors(all_errors_exit):<EOL><INDENT>module_vars = run_file(path)<EOL>self.vars.update(module_vars)<EOL>self.store("<STR_LIT>" + splitname(path)[<NUM_LIT:1>] + "<STR_LIT>")<EOL><DEDENT>
Execute a Python file.
f11263:c1:m7
def was_run_code(self, get_all=True):
if self.stored is None:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>if get_all:<EOL><INDENT>self.stored = ["<STR_LIT:\n>".join(self.stored)]<EOL><DEDENT>return self.stored[-<NUM_LIT:1>]<EOL><DEDENT>
Get all the code that was run.
f11263:c1:m8
def __init__(self, base, method):
self.recursion = sys.getrecursionlimit()<EOL>self.logger = copy(logger)<EOL>self.base, self.method = base, method<EOL>
Create new multiprocessable method.
f11263:c2:m0
def __call__(self, *args, **kwargs):
sys.setrecursionlimit(self.recursion)<EOL>logger.copy_from(self.logger)<EOL>return getattr(self.base, self.method)(*args, **kwargs)<EOL>
Set up new process then calls the method.
f11263:c2:m1
def keep_watching(self):
self.saw = set()<EOL>
Allows recompiling previously-compiled files.
f11264:c0:m1
def on_modified(self, event):
path = event.src_path<EOL>if path not in self.saw:<EOL><INDENT>self.saw.add(path)<EOL>self.recompile(path)<EOL><DEDENT>
Handle a file modified event.
f11264:c0:m2
def mypy_run(args):
logger.log_cmd(["<STR_LIT>"] + args)<EOL>try:<EOL><INDENT>stdout, stderr, exit_code = run(args)<EOL><DEDENT>except BaseException:<EOL><INDENT>traceback.print_exc()<EOL><DEDENT>else:<EOL><INDENT>for line in stdout.splitlines():<EOL><INDENT>yield line, False<EOL><DEDENT>for line in stderr.splitlines():<EOL><INDENT>yield ...
Runs mypy with given arguments and shows the result.
f11266:m0
def __init__(self):
self.prompt = Prompt()<EOL>
Create the CLI.
f11267:c0:m0
def start(self, run=False):
if run:<EOL><INDENT>args, argv = [], []<EOL>for i in range(<NUM_LIT:1>, len(sys.argv)):<EOL><INDENT>arg = sys.argv[i]<EOL>args.append(arg)<EOL>if not arg.startswith("<STR_LIT:->") and canparse(arguments, args[:-<NUM_LIT:1>]):<EOL><INDENT>argv = sys.argv[i + <NUM_LIT:1>:]<EOL>break<EOL><DEDENT><DEDENT>if "<STR_LIT>" in ...
Process command-line arguments.
f11267:c0:m1
def cmd(self, args=None, interact=True):
if args is None:<EOL><INDENT>parsed_args = arguments.parse_args()<EOL><DEDENT>else:<EOL><INDENT>parsed_args = arguments.parse_args(args)<EOL><DEDENT>self.exit_code = <NUM_LIT:0><EOL>with self.handling_exceptions():<EOL><INDENT>self.use_args(parsed_args, interact, original_args=args)<EOL><DEDENT>self.exit_on_error()<EOL...
Process command-line arguments.
f11267:c0:m2
def setup(self, *args, **kwargs):
if self.comp is None:<EOL><INDENT>self.comp = Compiler(*args, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>self.comp.setup(*args, **kwargs)<EOL><DEDENT>
Set parameters for the compiler.
f11267:c0:m3
def exit_on_error(self):
if self.exit_code:<EOL><INDENT>if self.errmsg is not None:<EOL><INDENT>logger.show("<STR_LIT>" + self.errmsg + "<STR_LIT:.>")<EOL>self.errmsg = None<EOL><DEDENT>if self.using_jobs:<EOL><INDENT>kill_children()<EOL><DEDENT>sys.exit(self.exit_code)<EOL><DEDENT>
Exit if exit_code is abnormal.
f11267:c0:m4
def use_args(self, args, interact=True, original_args=None):
logger.quiet, logger.verbose = args.quiet, args.verbose<EOL>if DEVELOP:<EOL><INDENT>logger.tracing = args.trace<EOL><DEDENT>logger.log("<STR_LIT>" + PYPARSING + "<STR_LIT:.>")<EOL>if original_args is not None:<EOL><INDENT>logger.log("<STR_LIT>", original_args)<EOL><DEDENT>logger.log("<STR_LIT>", args)<EOL>if args.recur...
Handle command-line arguments.
f11267:c0:m5
def register_error(self, code=<NUM_LIT:1>, errmsg=None):
if errmsg is not None:<EOL><INDENT>if self.errmsg is None:<EOL><INDENT>self.errmsg = errmsg<EOL><DEDENT>elif errmsg not in self.errmsg:<EOL><INDENT>self.errmsg += "<STR_LIT:U+002CU+0020>" + errmsg<EOL><DEDENT><DEDENT>if code is not None:<EOL><INDENT>self.exit_code = max(self.exit_code, code)<EOL><DEDENT>
Update the exit code.
f11267:c0:m6
@contextmanager<EOL><INDENT>def handling_exceptions(self):<DEDENT>
try:<EOL><INDENT>if self.using_jobs:<EOL><INDENT>with handling_broken_process_pool():<EOL><INDENT>yield<EOL><DEDENT><DEDENT>else:<EOL><INDENT>yield<EOL><DEDENT><DEDENT>except SystemExit as err:<EOL><INDENT>self.register_error(err.code)<EOL><DEDENT>except BaseException as err:<EOL><INDENT>if isinstance(err, CoconutExcep...
Perform proper exception handling.
f11267:c0:m7
def compile_path(self, path, write=True, package=None, *args, **kwargs):
path = fixpath(path)<EOL>if not isinstance(write, bool):<EOL><INDENT>write = fixpath(write)<EOL><DEDENT>if os.path.isfile(path):<EOL><INDENT>if package is None:<EOL><INDENT>package = False<EOL><DEDENT>destpath = self.compile_file(path, write, package, *args, **kwargs)<EOL>return [destpath] if destpath is not None else ...
Compile a path and returns paths to compiled files.
f11267:c0:m8
def compile_folder(self, directory, write=True, package=True, *args, **kwargs):
if not isinstance(write, bool) and os.path.isfile(write):<EOL><INDENT>raise CoconutException("<STR_LIT>")<EOL><DEDENT>filepaths = []<EOL>for dirpath, dirnames, filenames in os.walk(directory):<EOL><INDENT>if isinstance(write, bool):<EOL><INDENT>writedir = write<EOL><DEDENT>else:<EOL><INDENT>writedir = os.path.join(writ...
Compile a directory and returns paths to compiled files.
f11267:c0:m9
def compile_file(self, filepath, write=True, package=False, *args, **kwargs):
set_ext = False<EOL>if write is False:<EOL><INDENT>destpath = None<EOL><DEDENT>elif write is True:<EOL><INDENT>destpath = filepath<EOL>set_ext = True<EOL><DEDENT>elif os.path.splitext(write)[<NUM_LIT:1>]:<EOL><INDENT>destpath = write<EOL><DEDENT>else:<EOL><INDENT>destpath = os.path.join(write, os.path.basename(filepath...
Compile a file and returns the compiled file's path.
f11267:c0:m10
def compile(self, codepath, destpath=None, package=False, run=False, force=False, show_unchanged=True):
with openfile(codepath, "<STR_LIT:r>") as opened:<EOL><INDENT>code = readfile(opened)<EOL><DEDENT>if destpath is not None:<EOL><INDENT>destdir = os.path.dirname(destpath)<EOL>if not os.path.exists(destdir):<EOL><INDENT>os.makedirs(destdir)<EOL><DEDENT>if package is True:<EOL><INDENT>self.create_package(destdir)<EOL><DE...
Compile a source Coconut file to a destination Python file.
f11267:c0:m11
def submit_comp_job(self, path, callback, method, *args, **kwargs):
if self.executor is None:<EOL><INDENT>with self.handling_exceptions():<EOL><INDENT>callback(getattr(self.comp, method)(*args, **kwargs))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>path = showpath(path)<EOL>with logger.in_path(path): <EOL><INDENT>future = self.executor.submit(multiprocess_wrapper(self.comp, method), *args, ...
Submits a job on self.comp to be run in parallel.
f11267:c0:m12
def set_jobs(self, jobs):
if jobs == "<STR_LIT>":<EOL><INDENT>self.jobs = None<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>jobs = int(jobs)<EOL><DEDENT>except ValueError:<EOL><INDENT>jobs = -<NUM_LIT:1> <EOL><DEDENT>if jobs < <NUM_LIT:0>:<EOL><INDENT>raise CoconutException("<STR_LIT>")<EOL><DEDENT>self.jobs = jobs<EOL><DEDENT>
Set --jobs.
f11267:c0:m13
@property<EOL><INDENT>def using_jobs(self):<DEDENT>
return self.jobs != <NUM_LIT:0><EOL>
Determine whether or not multiprocessing is being used.
f11267:c0:m14
@contextmanager<EOL><INDENT>def running_jobs(self, exit_on_error=True):<DEDENT>
with self.handling_exceptions():<EOL><INDENT>if self.using_jobs:<EOL><INDENT>from concurrent.futures import ProcessPoolExecutor<EOL>try:<EOL><INDENT>with ProcessPoolExecutor(self.jobs) as self.executor:<EOL><INDENT>yield<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>self.executor = None<EOL><DEDENT><DEDENT>else:<EOL><INDENT...
Initialize multiprocessing.
f11267:c0:m15
def create_package(self, dirpath):
dirpath = fixpath(dirpath)<EOL>filepath = os.path.join(dirpath, "<STR_LIT>")<EOL>with openfile(filepath, "<STR_LIT:w>") as opened:<EOL><INDENT>writefile(opened, self.comp.getheader("<STR_LIT>"))<EOL><DEDENT>
Set up a package directory.
f11267:c0:m16
def has_hash_of(self, destpath, code, package):
if destpath is not None and os.path.isfile(destpath):<EOL><INDENT>with openfile(destpath, "<STR_LIT:r>") as opened:<EOL><INDENT>compiled = readfile(opened)<EOL><DEDENT>hashash = gethash(compiled)<EOL>if hashash is not None and hashash == self.comp.genhash(package, code):<EOL><INDENT>return compiled<EOL><DEDENT><DEDENT>...
Determine if a file has the hash of the code.
f11267:c0:m17
def get_input(self, more=False):
received = None<EOL>try:<EOL><INDENT>received = self.prompt.input(more)<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>print()<EOL>printerr("<STR_LIT>")<EOL><DEDENT>except EOFError:<EOL><INDENT>print()<EOL>self.exit_runner()<EOL><DEDENT>else:<EOL><INDENT>if received.startswith(exit_chars):<EOL><INDENT>self.exit_runn...
Prompt for code input.
f11267:c0:m18
def start_running(self):
self.comp.warm_up()<EOL>self.check_runner()<EOL>self.running = True<EOL>
Start running the Runner.
f11267:c0:m19
def start_prompt(self):
logger.show("<STR_LIT>")<EOL>logger.show("<STR_LIT>")<EOL>self.start_running()<EOL>while self.running:<EOL><INDENT>try:<EOL><INDENT>code = self.get_input()<EOL>if code:<EOL><INDENT>compiled = self.handle_input(code)<EOL>if compiled:<EOL><INDENT>self.execute(compiled, use_eval=None)<EOL><DEDENT><DEDENT><DEDENT>except Ke...
Start the interpreter.
f11267:c0:m20
def exit_runner(self, exit_code=<NUM_LIT:0>):
self.register_error(exit_code)<EOL>self.running = False<EOL>
Exit the interpreter.
f11267:c0:m21
def handle_input(self, code):
if not self.prompt.multiline:<EOL><INDENT>if not should_indent(code):<EOL><INDENT>try:<EOL><INDENT>return self.comp.parse_block(code)<EOL><DEDENT>except CoconutException:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>while True:<EOL><INDENT>line = self.get_input(more=True)<EOL>if line is None:<EOL><INDENT>return None<EOL><DEDEN...
Compile Coconut interpreter input.
f11267:c0:m22
def execute(self, compiled=None, path=None, use_eval=False, allow_show=True):
self.check_runner()<EOL>if compiled is not None:<EOL><INDENT>if allow_show and self.show:<EOL><INDENT>print(compiled)<EOL><DEDENT>if path is not None: <EOL><INDENT>compiled = rem_encoding(compiled)<EOL><DEDENT>self.runner.run(compiled, use_eval=use_eval, path=path, all_errors_exit=(path is not None))<EOL>self.run_mypy...
Execute compiled code.
f11267:c0:m23
def execute_file(self, destpath):
self.check_runner()<EOL>self.runner.run_file(destpath)<EOL>
Execute compiled file.
f11267:c0:m24
def check_runner(self):
if os.getcwd() not in sys.path:<EOL><INDENT>sys.path.append(os.getcwd())<EOL><DEDENT>if self.runner is None:<EOL><INDENT>self.runner = Runner(self.comp, exit=self.exit_runner, store=self.mypy)<EOL><DEDENT>
Make sure there is a runner.
f11267:c0:m25
@property<EOL><INDENT>def mypy(self):<DEDENT>
return self.mypy_args is not None<EOL>
Whether using MyPy or not.
f11267:c0:m26
def set_mypy_args(self, mypy_args=None):
if mypy_args is None:<EOL><INDENT>self.mypy_args = None<EOL><DEDENT>else:<EOL><INDENT>self.mypy_errs = []<EOL>self.mypy_args = list(mypy_args)<EOL>if not any(arg.startswith("<STR_LIT>") for arg in mypy_args):<EOL><INDENT>self.mypy_args += [<EOL>"<STR_LIT>",<EOL>"<STR_LIT:.>".join(str(v) for v in get_target_info_len2(se...
Set MyPy arguments.
f11267:c0:m27
def run_mypy(self, paths=(), code=None):
if self.mypy:<EOL><INDENT>set_mypy_path(stub_dir)<EOL>from coconut.command.mypy import mypy_run<EOL>args = list(paths) + self.mypy_args<EOL>if code is not None:<EOL><INDENT>args += ["<STR_LIT:-c>", code]<EOL><DEDENT>for line, is_err in mypy_run(args):<EOL><INDENT>if code is None or line not in self.mypy_errs:<EOL><INDE...
Run MyPy with arguments.
f11267:c0:m28
def start_jupyter(self, args):
install_func = partial(run_cmd, show_output=logger.verbose)<EOL>try:<EOL><INDENT>install_func(["<STR_LIT>", "<STR_LIT>"])<EOL><DEDENT>except CalledProcessError:<EOL><INDENT>jupyter = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>jupyter = "<STR_LIT>"<EOL><DEDENT>do_install = not args<EOL>if not do_install:<EOL><INDENT>kern...
Start Jupyter with the Coconut kernel.
f11267:c0:m29
def watch(self, source, write=True, package=None, run=False, force=False):
from coconut.command.watch import Observer, RecompilationWatcher<EOL>source = fixpath(source)<EOL>logger.show()<EOL>logger.show_tabulated("<STR_LIT>", showpath(source), "<STR_LIT>")<EOL>def recompile(path):<EOL><INDENT>path = fixpath(path)<EOL>if os.path.isfile(path) and os.path.splitext(path)[<NUM_LIT:1>] in code_exts...
Watch a source and recompiles on change.
f11267:c0:m30
def load_ipython_extension(ipython):
<EOL>from coconut import __coconut__<EOL>newvars = {}<EOL>for var, val in vars(__coconut__).items():<EOL><INDENT>if not var.startswith("<STR_LIT>"):<EOL><INDENT>newvars[var] = val<EOL><DEDENT><DEDENT>ipython.push(newvars)<EOL>from coconut.convenience import cmd, parse, CoconutException<EOL>from coconut.terminal import ...
Loads Coconut as an IPython extension.
f11269:m0
def get_reqs(which="<STR_LIT>"):
reqs = []<EOL>for req in all_reqs[which]:<EOL><INDENT>req_str = req + "<STR_LIT>" + ver_tuple_to_str(min_versions[req])<EOL>if req in version_strictly:<EOL><INDENT>req_str += "<STR_LIT>" + ver_tuple_to_str(min_versions[req][:-<NUM_LIT:1>]) + "<STR_LIT:.>" + str(min_versions[req][-<NUM_LIT:1>] + <NUM_LIT:1>)<EOL><DEDENT...
Gets requirements from all_reqs with versions.
f11271:m0
def uniqueify(reqs):
return list(set(reqs))<EOL>
Make a list of requirements unique.
f11271:m1
def uniqueify_all(init_reqs, *other_reqs):
union = set(init_reqs)<EOL>for reqs in other_reqs:<EOL><INDENT>union.update(reqs)<EOL><DEDENT>return list(union)<EOL>
Find the union of all the given requirements.
f11271:m2
def unique_wrt(reqs, main_reqs):
return list(set(reqs) - set(main_reqs))<EOL>
Ensures reqs doesn't contain anything in main_reqs.
f11271:m3
def everything_in(req_dict):
return uniqueify(req for req_list in req_dict.values() for req in req_list)<EOL>
Gets all requirements in a requirements dict.
f11271:m4
def all_versions(req):
import requests<EOL>url = "<STR_LIT>" + req + "<STR_LIT>"<EOL>return tuple(requests.get(url).json()["<STR_LIT>"].keys())<EOL>
Get all versions of req from PyPI.
f11271:m5
def newer(new_ver, old_ver, strict=False):
if old_ver == new_ver or old_ver + (<NUM_LIT:0>,) == new_ver:<EOL><INDENT>return False<EOL><DEDENT>for n, o in zip(new_ver, old_ver):<EOL><INDENT>if not isinstance(n, int):<EOL><INDENT>o = str(o)<EOL><DEDENT>if o < n:<EOL><INDENT>return True<EOL><DEDENT>elif o > n:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return no...
Determines if the first version tuple is newer than the second. True if newer, False if older, None if difference is after specified version parts.
f11271:m6
def print_new_versions(strict=False):
new_updates = []<EOL>same_updates = []<EOL>for req in everything_in(all_reqs):<EOL><INDENT>new_versions = []<EOL>same_versions = []<EOL>for ver_str in all_versions(req):<EOL><INDENT>if newer(ver_str_to_tuple(ver_str), min_versions[req], strict=True):<EOL><INDENT>new_versions.append(ver_str)<EOL><DEDENT>elif not strict ...
Prints new requirement versions.
f11271:m7
def lenient_add_filter(self, *args, **kwargs):
if args and args[<NUM_LIT:0>] != "<STR_LIT>":<EOL><INDENT>self.original_add_filter(*args, **kwargs)<EOL><DEDENT>
Disables the raiseonerror filter.
f11272:m0
def __init__(self, stripnl=False, stripall=False, ensurenl=True, tabsize=tabideal, encoding=default_encoding):
Python3Lexer.__init__(self, stripnl=stripnl, stripall=stripall, ensurenl=ensurenl, tabsize=tabsize, encoding=default_encoding)<EOL>self.original_add_filter, self.add_filter = self.add_filter, lenient_add_filter<EOL>
Initialize the Python syntax highlighter.
f11272:c0:m0
def __init__(self, stripnl=False, stripall=False, ensurenl=True, tabsize=tabideal, encoding=default_encoding, python3=True):
PythonConsoleLexer.__init__(self, stripnl=stripnl, stripall=stripall, ensurenl=ensurenl, tabsize=tabsize, encoding=default_encoding, python3=python3)<EOL>self.original_add_filter, self.add_filter = self.add_filter, lenient_add_filter<EOL>
Initialize the Python console syntax highlighter.
f11272:c1:m0
def __init__(self, stripnl=False, stripall=False, ensurenl=True, tabsize=tabideal, encoding=default_encoding):
Python3Lexer.__init__(self, stripnl=stripnl, stripall=stripall, ensurenl=ensurenl, tabsize=tabsize, encoding=default_encoding)<EOL>self.original_add_filter, self.add_filter = self.add_filter, lenient_add_filter<EOL>
Initialize the Python syntax highlighter.
f11272:c2:m0
def main():
IPKernelApp.launch_instance(kernel_class=CoconutKernel)<EOL>
Launch the kernel app.
f11273:m0
def memoized_parse_block(code):
success, result = parse_block_memo.get(code, (None, None))<EOL>if success is None:<EOL><INDENT>try:<EOL><INDENT>parsed = COMPILER.parse_block(code)<EOL><DEDENT>except Exception as err:<EOL><INDENT>success, result = False, err<EOL><DEDENT>else:<EOL><INDENT>success, result = True, parsed<EOL><DEDENT>parse_block_memo[code...
Memoized version of parse_block.
f11275:m0
def memoized_parse_sys(code):
return COMPILER.header_proc(memoized_parse_block(code), header="<STR_LIT>", initial="<STR_LIT:none>")<EOL>
Memoized version of parse_sys.
f11275:m1
def _indent(code, by=<NUM_LIT:1>):
return "<STR_LIT>".join(<EOL>("<STR_LIT:U+0020>" * by if line else "<STR_LIT>") + line for line in code.splitlines(True)<EOL>)<EOL>
Indents every nonempty line of the given code.
f11277:m0
def get_encoding(fileobj):
<EOL>obj_encoding = getattr(fileobj, "<STR_LIT>", None)<EOL>return obj_encoding if obj_encoding is not None else default_encoding<EOL>
Get encoding of a file.
f11278:m0
def clean(inputline, strip=True, rem_indents=True, encoding_errors="<STR_LIT:replace>"):
stdout_encoding = get_encoding(sys.stdout)<EOL>inputline = str(inputline)<EOL>if rem_indents:<EOL><INDENT>inputline = inputline.replace(openindent, "<STR_LIT>").replace(closeindent, "<STR_LIT>")<EOL><DEDENT>if strip:<EOL><INDENT>inputline = inputline.strip()<EOL><DEDENT>return inputline.encode(stdout_encoding, encoding...
Clean and strip a line.
f11278:m1
def displayable(inputstr, strip=True):
return clean(str(inputstr), strip, rem_indents=False, encoding_errors="<STR_LIT>")<EOL>
Make a string displayable with minimal loss of information.
f11278:m2
def internal_assert(condition, message=None, item=None, extra=None):
if DEVELOP and callable(condition):<EOL><INDENT>condition = condition()<EOL><DEDENT>if not condition:<EOL><INDENT>if message is None:<EOL><INDENT>message = "<STR_LIT>"<EOL>if item is None:<EOL><INDENT>item = condition<EOL><DEDENT><DEDENT>raise CoconutInternalException(message, item, extra)<EOL><DEDENT>
Raise InternalException if condition is False. If condition is a function, execute it on DEVELOP only.
f11278:m3
def __init__(self, message, item=None, extra=None):
self.args = (message, item, extra)<EOL>
Creates the Coconut exception.
f11278:c0:m0
def message(self, message, item, extra):
if item is not None:<EOL><INDENT>message += "<STR_LIT>" + ascii(item)<EOL><DEDENT>if extra is not None:<EOL><INDENT>message += "<STR_LIT>" + str(extra) + "<STR_LIT:)>"<EOL><DEDENT>return message<EOL>
Uses arguments to create the message.
f11278:c0:m1
def syntax_err(self):
return SyntaxError(str(self))<EOL>
Converts to a SyntaxError.
f11278:c0:m2
def __str__(self):
return self.message(*self.args)<EOL>
Get the exception message.
f11278:c0:m3
def __reduce__(self):
return (self.__class__, self.args)<EOL>
Get pickling information.
f11278:c0:m4
def __repr__(self):
return self.__class__.__name__ + "<STR_LIT:(>" + "<STR_LIT:U+002CU+0020>".join(<EOL>repr(arg) for arg in self.args if arg is not None<EOL>) + "<STR_LIT:)>"<EOL>
Get a representation of the exception.
f11278:c0:m5
def __init__(self, message, source=None, point=None, ln=None):
self.args = (message, source, point, ln)<EOL>
Creates the Coconut SyntaxError.
f11278:c1:m0