Instruction:
Write a Python 3 script for
returning a Python AST Node for a let expression.

Response:
def _let_to_py_ast(ctx: GeneratorContext, node: Let) -> GeneratedPyAST:
    """Return a Python AST Node for a `let*` expression."""
    assert node.op == NodeOp.LET

    with ctx.new_symbol_table("let"):
        let_body_ast: List[ast.AST] = []
        for binding in node.bindings:
            init_node = binding.init
            assert init_node is not None
            init_ast = gen_py_ast(ctx, init_node)
            binding_name = genname(munge(binding.name))
            let_body_ast.extend(init_ast.dependencies)
            let_body_ast.append(
                ast.Assign(
                    targets=[ast.Name(id=binding_name, ctx=ast.Store())],
                    value=init_ast.node,
                )
            )
            ctx.symbol_table.new_symbol(
                sym.symbol(binding.name), binding_name, LocalType.LET
            )

        let_result_name = genname("let_result")
        body_ast = _synthetic_do_to_py_ast(ctx, node.body)
        let_body_ast.extend(map(statementize, body_ast.dependencies))
        let_body_ast.append(
            ast.Assign(
                targets=[ast.Name(id=let_result_name, ctx=ast.Store())],
                value=body_ast.node,
            )
        )

        return GeneratedPyAST(
            node=ast.Name(id=let_result_name, ctx=ast.Load()), dependencies=let_body_ast
        )


Instruction:
Write a Python 3 script for
returning a Python AST Node for a loop expression.

Response:
def _loop_to_py_ast(ctx: GeneratorContext, node: Loop) -> GeneratedPyAST:
    """Return a Python AST Node for a `loop*` expression."""
    assert node.op == NodeOp.LOOP

    with ctx.new_symbol_table("loop"):
        binding_names = []
        init_bindings: List[ast.AST] = []
        for binding in node.bindings:
            init_node = binding.init
            assert init_node is not None
            init_ast = gen_py_ast(ctx, init_node)
            init_bindings.extend(init_ast.dependencies)
            binding_name = genname(munge(binding.name))
            binding_names.append(binding_name)
            init_bindings.append(
                ast.Assign(
                    targets=[ast.Name(id=binding_name, ctx=ast.Store())],
                    value=init_ast.node,
                )
            )
            ctx.symbol_table.new_symbol(
                sym.symbol(binding.name), binding_name, LocalType.LOOP
            )

        loop_result_name = genname("loop")
        with ctx.new_recur_point(
            node.loop_id, RecurType.LOOP, binding_names=binding_names
        ):
            loop_body_ast: List[ast.AST] = []
            body_ast = _synthetic_do_to_py_ast(ctx, node.body)
            loop_body_ast.extend(body_ast.dependencies)
            loop_body_ast.append(
                ast.Assign(
                    targets=[ast.Name(id=loop_result_name, ctx=ast.Store())],
                    value=body_ast.node,
                )
            )
            loop_body_ast.append(ast.Break())

            return GeneratedPyAST(
                node=_load_attr(loop_result_name),
                dependencies=list(
                    chain(
                        [
                            ast.Assign(
                                targets=[
                                    ast.Name(id=loop_result_name, ctx=ast.Store())
                                ],
                                value=ast.NameConstant(None),
                            )
                        ],
                        init_bindings,
                        [
                            ast.While(
                                test=ast.NameConstant(True),
                                body=loop_body_ast,
                                orelse=[],
                            )
                        ],
                    )
                ),
            )


Instruction:
Given the following Python 3 function, write the documentation
def _quote_to_py_ast(ctx: GeneratorContext, node: Quote) -> GeneratedPyAST:
    assert node.op == NodeOp.QUOTE
    return _const_node_to_py_ast(ctx, node.expr)

Response: Return a Python AST Node for a quote expression.


Instruction:
How would you explain what the following Python 3 function does
def __fn_recur_to_py_ast(ctx: GeneratorContext, node: Recur) -> GeneratedPyAST:
    assert node.op == NodeOp.RECUR
    assert ctx.recur_point.is_variadic is not None
    recur_nodes: List[ast.AST] = []
    recur_deps: List[ast.AST] = []
    for expr in node.exprs:
        expr_ast = gen_py_ast(ctx, expr)
        recur_nodes.append(expr_ast.node)
        recur_deps.extend(expr_ast.dependencies)

    return GeneratedPyAST(
        node=ast.Call(
            func=_TRAMPOLINE_ARGS_FN_NAME,
            args=list(
                chain([ast.NameConstant(ctx.recur_point.is_variadic)], recur_nodes)
            ),
            keywords=[],
        ),
        dependencies=recur_deps,
    )

Response: Return a Python AST node for a given recur.


Instruction:
Write a Python 3 script to
return a Python AST node for recur occurring inside a deftype * method.

Response:
def __deftype_method_recur_to_py_ast(
    ctx: GeneratorContext, node: Recur
) -> GeneratedPyAST:
    """Return a Python AST node for `recur` occurring inside a `deftype*` method."""
    assert node.op == NodeOp.RECUR
    recur_nodes: List[ast.AST] = []
    recur_deps: List[ast.AST] = []
    for expr in node.exprs:
        expr_ast = gen_py_ast(ctx, expr)
        recur_nodes.append(expr_ast.node)
        recur_deps.extend(expr_ast.dependencies)

    this_entry = ctx.symbol_table.find_symbol(ctx.current_this)
    assert this_entry is not None, "Field type local must have this"

    return GeneratedPyAST(
        node=ast.Call(
            func=_TRAMPOLINE_ARGS_FN_NAME,
            args=list(
                chain(
                    [
                        ast.NameConstant(ctx.recur_point.is_variadic),
                        ast.Name(id=this_entry.munged, ctx=ast.Load()),
                    ],
                    recur_nodes,
                )
            ),
            keywords=[],
        ),
        dependencies=recur_deps,
    )


Instruction:
Can you create a Python 3 function that
returns a Python AST node for a loop occurring inside a loop.

Response:
def __loop_recur_to_py_ast(ctx: GeneratorContext, node: Recur) -> GeneratedPyAST:
    """Return a Python AST node for `recur` occurring inside a `loop`."""
    assert node.op == NodeOp.RECUR

    recur_deps: List[ast.AST] = []
    recur_targets: List[ast.Name] = []
    recur_exprs: List[ast.AST] = []
    for name, expr in zip(ctx.recur_point.binding_names, node.exprs):
        expr_ast = gen_py_ast(ctx, expr)
        recur_deps.extend(expr_ast.dependencies)
        recur_targets.append(ast.Name(id=name, ctx=ast.Store()))
        recur_exprs.append(expr_ast.node)

    if len(recur_targets) == 1:
        assert len(recur_exprs) == 1
        recur_deps.append(ast.Assign(targets=recur_targets, value=recur_exprs[0]))
    else:
        recur_deps.append(
            ast.Assign(
                targets=[ast.Tuple(elts=recur_targets, ctx=ast.Store())],
                value=ast.Tuple(elts=recur_exprs, ctx=ast.Load()),
            )
        )
    recur_deps.append(ast.Continue())

    return GeneratedPyAST(node=ast.NameConstant(None), dependencies=recur_deps)


Instruction:
How would you code a function in Python 3 to
return a Python AST Node for a recur expression.

Response:
def _recur_to_py_ast(ctx: GeneratorContext, node: Recur) -> GeneratedPyAST:
    """Return a Python AST Node for a `recur` expression.

    Note that `recur` nodes can only legally appear in two AST locations:
      (1) in :then or :else expressions in :if nodes, and
      (2) in :ret expressions in :do nodes

    As such, both of these handlers special case the recur construct, as it
    is the only case in which the code generator emits a statement rather than
    an expression."""
    assert node.op == NodeOp.RECUR
    assert ctx.recur_point is not None, "Must have set a recur point to recur"
    handle_recur = _RECUR_TYPE_HANDLER.get(ctx.recur_point.type)
    assert (
        handle_recur is not None
    ), f"No recur point handler defined for {ctx.recur_point.type}"
    ctx.recur_point.has_recur = True
    return handle_recur(ctx, node)


Instruction:
Here you have a function in Python 3, explain what it does
def _set_bang_to_py_ast(ctx: GeneratorContext, node: SetBang) -> GeneratedPyAST:
    assert node.op == NodeOp.SET_BANG

    val_temp_name = genname("set_bang_val")
    val_ast = gen_py_ast(ctx, node.val)

    target = node.target
    assert isinstance(
        target, (HostField, Local, VarRef)
    ), f"invalid set! target type {type(target)}"

    if isinstance(target, HostField):
        target_ast = _interop_prop_to_py_ast(ctx, target, is_assigning=True)
    elif isinstance(target, VarRef):
        target_ast = _var_sym_to_py_ast(ctx, target, is_assigning=True)
    elif isinstance(target, Local):
        target_ast = _local_sym_to_py_ast(ctx, target, is_assigning=True)
    else:  # pragma: no cover
        raise GeneratorException(
            f"invalid set! target type {type(target)}", lisp_ast=target
        )

    return GeneratedPyAST(
        node=ast.Name(id=val_temp_name, ctx=ast.Load()),
        dependencies=list(
            chain(
                val_ast.dependencies,
                [
                    ast.Assign(
                        targets=[ast.Name(id=val_temp_name, ctx=ast.Store())],
                        value=val_ast.node,
                    )
                ],
                target_ast.dependencies,
                [ast.Assign(targets=[target_ast.node], value=val_ast.node)],
            )
        ),
    )

Response: Return a Python AST Node for a set! expression.


Instruction:
Explain what the following Python 3 code does
def _throw_to_py_ast(ctx: GeneratorContext, node: Throw) -> GeneratedPyAST:
    assert node.op == NodeOp.THROW

    throw_fn = genname(_THROW_PREFIX)
    exc_ast = gen_py_ast(ctx, node.exception)
    raise_body = ast.Raise(exc=exc_ast.node, cause=None)

    return GeneratedPyAST(
        node=ast.Call(func=ast.Name(id=throw_fn, ctx=ast.Load()), args=[], keywords=[]),
        dependencies=[
            ast.FunctionDef(
                name=throw_fn,
                args=ast.arguments(
                    args=[],
                    kwarg=None,
                    vararg=None,
                    kwonlyargs=[],
                    defaults=[],
                    kw_defaults=[],
                ),
                body=list(chain(exc_ast.dependencies, [raise_body])),
                decorator_list=[],
                returns=None,
            )
        ],
    )

Response: Return a Python AST Node for a Throw expression.


Instruction:
Write a Python 3 function that can
return a Python AST Node for a try expression.

Response:
def _try_to_py_ast(ctx: GeneratorContext, node: Try) -> GeneratedPyAST:
    """Return a Python AST Node for a `try` expression."""
    assert node.op == NodeOp.TRY

    try_expr_name = genname("try_expr")

    body_ast = _synthetic_do_to_py_ast(ctx, node.body)
    catch_handlers = list(
        map(partial(__catch_to_py_ast, ctx, try_expr_name=try_expr_name), node.catches)
    )

    finallys: List[ast.AST] = []
    if node.finally_ is not None:
        finally_ast = _synthetic_do_to_py_ast(ctx, node.finally_)
        finallys.extend(map(statementize, finally_ast.dependencies))
        finallys.append(statementize(finally_ast.node))

    return GeneratedPyAST(
        node=ast.Name(id=try_expr_name, ctx=ast.Load()),
        dependencies=[
            ast.Try(
                body=list(
                    chain(
                        body_ast.dependencies,
                        [
                            ast.Assign(
                                targets=[ast.Name(id=try_expr_name, ctx=ast.Store())],
                                value=body_ast.node,
                            )
                        ],
                    )
                ),
                handlers=catch_handlers,
                orelse=[],
                finalbody=finallys,
            )
        ],
    )


Instruction:
Can you implement a function in Python 3 that
generates a Python AST node for accessing a locally defined Python variable.

Response:
def _local_sym_to_py_ast(
    ctx: GeneratorContext, node: Local, is_assigning: bool = False
) -> GeneratedPyAST:
    """Generate a Python AST node for accessing a locally defined Python variable."""
    assert node.op == NodeOp.LOCAL

    sym_entry = ctx.symbol_table.find_symbol(sym.symbol(node.name))
    assert sym_entry is not None

    if node.local == LocalType.FIELD:
        this_entry = ctx.symbol_table.find_symbol(ctx.current_this)
        assert this_entry is not None, "Field type local must have this"

        return GeneratedPyAST(
            node=_load_attr(
                f"{this_entry.munged}.{sym_entry.munged}",
                ctx=ast.Store() if is_assigning else ast.Load(),
            )
        )
    else:
        return GeneratedPyAST(
            node=ast.Name(
                id=sym_entry.munged, ctx=ast.Store() if is_assigning else ast.Load()
            )
        )


Instruction:
Can you implement a function in Python 3 that
generates Var. find calls for the named symbol.

Response:
def __var_find_to_py_ast(
    var_name: str, ns_name: str, py_var_ctx: ast.AST
) -> GeneratedPyAST:
    """Generate Var.find calls for the named symbol."""
    return GeneratedPyAST(
        node=ast.Attribute(
            value=ast.Call(
                func=_FIND_VAR_FN_NAME,
                args=[
                    ast.Call(
                        func=_NEW_SYM_FN_NAME,
                        args=[ast.Str(var_name)],
                        keywords=[ast.keyword(arg="ns", value=ast.Str(ns_name))],
                    )
                ],
                keywords=[],
            ),
            attr="value",
            ctx=py_var_ctx,
        )
    )


Instruction:
Write a Python 3 script for
generating a Python AST node for accessing a Var.

Response:
def _var_sym_to_py_ast(
    ctx: GeneratorContext, node: VarRef, is_assigning: bool = False
) -> GeneratedPyAST:
    """Generate a Python AST node for accessing a Var.

    If the Var is marked as :dynamic or :redef or the compiler option
    USE_VAR_INDIRECTION is active, do not compile to a direct access.
    If the corresponding function name is not defined in a Python module,
    no direct variable access is possible and Var.find indirection must be
    used."""
    assert node.op == NodeOp.VAR

    var = node.var
    ns = var.ns
    ns_name = ns.name
    ns_module = ns.module
    safe_ns = munge(ns_name)
    var_name = var.name.name
    py_var_ctx = ast.Store() if is_assigning else ast.Load()

    # Return the actual var, rather than its value if requested
    if node.return_var:
        return GeneratedPyAST(
            node=ast.Call(
                func=_FIND_VAR_FN_NAME,
                args=[
                    ast.Call(
                        func=_NEW_SYM_FN_NAME,
                        args=[ast.Str(var_name)],
                        keywords=[ast.keyword(arg="ns", value=ast.Str(ns_name))],
                    )
                ],
                keywords=[],
            )
        )

    # Check if we should use Var indirection
    if ctx.use_var_indirection or _is_dynamic(var) or _is_redefable(var):
        return __var_find_to_py_ast(var_name, ns_name, py_var_ctx)

    # Otherwise, try to direct-link it like a Python variable
    # Try without allowing builtins first
    safe_name = munge(var_name)
    if safe_name not in ns_module.__dict__:
        # Try allowing builtins
        safe_name = munge(var_name, allow_builtins=True)

    if safe_name in ns_module.__dict__:
        if ns is ctx.current_ns:
            return GeneratedPyAST(node=ast.Name(id=safe_name, ctx=py_var_ctx))
        return GeneratedPyAST(node=_load_attr(f"{safe_ns}.{safe_name}", ctx=py_var_ctx))

    if ctx.warn_on_var_indirection:
        logger.warning(f"could not resolve a direct link to Var '{var_name}'")

    return __var_find_to_py_ast(var_name, ns_name, py_var_ctx)


Instruction:
Create a Python 3 function to
generate a Python AST node for Python interop method calls.

Response:
def _interop_call_to_py_ast(ctx: GeneratorContext, node: HostCall) -> GeneratedPyAST:
    """Generate a Python AST node for Python interop method calls."""
    assert node.op == NodeOp.HOST_CALL

    target_ast = gen_py_ast(ctx, node.target)
    args_deps, args_nodes = _collection_ast(ctx, node.args)

    return GeneratedPyAST(
        node=ast.Call(
            func=ast.Attribute(
                value=target_ast.node,
                attr=munge(node.method, allow_builtins=True),
                ctx=ast.Load(),
            ),
            args=list(args_nodes),
            keywords=[],
        ),
        dependencies=list(chain(target_ast.dependencies, args_deps)),
    )


Instruction:
Write a Python 3 script to
generate a Python AST node for Python interop property access.

Response:
def _interop_prop_to_py_ast(
    ctx: GeneratorContext, node: HostField, is_assigning: bool = False
) -> GeneratedPyAST:
    """Generate a Python AST node for Python interop property access."""
    assert node.op == NodeOp.HOST_FIELD

    target_ast = gen_py_ast(ctx, node.target)

    return GeneratedPyAST(
        node=ast.Attribute(
            value=target_ast.node,
            attr=munge(node.field),
            ctx=ast.Store() if is_assigning else ast.Load(),
        ),
        dependencies=target_ast.dependencies,
    )


Instruction:
How would you explain what the following Python 3 function does
def _maybe_class_to_py_ast(_: GeneratorContext, node: MaybeClass) -> GeneratedPyAST:
    assert node.op == NodeOp.MAYBE_CLASS
    return GeneratedPyAST(
        node=ast.Name(
            id=Maybe(_MODULE_ALIASES.get(node.class_)).or_else_get(node.class_),
            ctx=ast.Load(),
        )
    )

Response:
Generate a Python AST node for accessing a potential Python module
    variable name.


Instruction:
Create a Python 3 function to
generate a Python AST node for accessing a potential Python module variable name with a namespace.

Response:
def _maybe_host_form_to_py_ast(
    _: GeneratorContext, node: MaybeHostForm
) -> GeneratedPyAST:
    """Generate a Python AST node for accessing a potential Python module
    variable name with a namespace."""
    assert node.op == NodeOp.MAYBE_HOST_FORM
    return GeneratedPyAST(
        node=_load_attr(
            f"{Maybe(_MODULE_ALIASES.get(node.class_)).or_else_get(node.class_)}.{node.field}"
        )
    )


Instruction:
Explain what the following Python 3 code does
def _with_meta_to_py_ast(
    ctx: GeneratorContext, node: WithMeta, **kwargs
) -> GeneratedPyAST:
    """Generate a Python AST node for Python interop method calls."""
    assert node.op == NodeOp.WITH_META

    handle_expr = _WITH_META_EXPR_HANDLER.get(node.expr.op)
    assert (
        handle_expr is not None
    ), "No expression handler for with-meta child node type"
    return handle_expr(ctx, node.expr, meta_node=node.meta, **kwargs)

Response: Generate a Python AST node for Python interop method calls.


Instruction:
How would you explain what the following Python 3 function does
def _const_val_to_py_ast(ctx: GeneratorContext, form: LispForm) -> GeneratedPyAST:
    handle_value = _CONST_VALUE_HANDLERS.get(type(form))
    if handle_value is None and isinstance(form, ISeq):
        handle_value = _const_seq_to_py_ast  # type: ignore
    assert handle_value is not None, "A type handler must be defined for constants"
    return handle_value(ctx, form)

Response: Generate Python AST nodes for a constant Lisp form.


Instruction:
Can you implement a function in Python 3 that
turns a quoted collection literal of Lisp forms into Python AST nodes.

Response:
def _collection_literal_to_py_ast(
    ctx: GeneratorContext, form: Iterable[LispForm]
) -> Iterable[GeneratedPyAST]:
    """Turn a quoted collection literal of Lisp forms into Python AST nodes.

    This function can only handle constant values. It does not call back into
    the generic AST generators, so only constant values will be generated down
    this path."""
    yield from map(partial(_const_val_to_py_ast, ctx), form)


Instruction:
Create a Python 3 function to
generate Python AST nodes for a const Lisp AST node.

Response:
def _const_node_to_py_ast(ctx: GeneratorContext, lisp_ast: Const) -> GeneratedPyAST:
    """Generate Python AST nodes for a :const Lisp AST node.

    Nested values in collections for :const nodes are not parsed. Consequently,
    this function cannot be called recursively for those nested values. Instead,
    call `_const_val_to_py_ast` on nested values."""
    assert lisp_ast.op == NodeOp.CONST
    node_type = lisp_ast.type
    handle_const_node = _CONSTANT_HANDLER.get(node_type)
    assert handle_const_node is not None, f"No :const AST type handler for {node_type}"
    node_val = lisp_ast.val
    return handle_const_node(ctx, node_val)


Instruction:
Write a Python 3 script to
take a Lisp AST node as an argument and produce zero or more Python AST nodes.

Response:
def gen_py_ast(ctx: GeneratorContext, lisp_ast: Node) -> GeneratedPyAST:
    """Take a Lisp AST node as an argument and produce zero or more Python
    AST nodes.

    This is the primary entrypoint for generating AST nodes from Lisp
    syntax. It may be called recursively to compile child forms."""
    op: NodeOp = lisp_ast.op
    assert op is not None, "Lisp AST nodes must have an :op key"
    handle_node = _NODE_HANDLERS.get(op)
    assert (
        handle_node is not None
    ), f"Lisp AST nodes :op has no handler defined for op {op}"
    return handle_node(ctx, lisp_ast)


Instruction:
Given the following Python 3 function, write the documentation
def _module_imports(ctx: GeneratorContext) -> Iterable[ast.Import]:
    # Yield `import basilisp` so code attempting to call fully qualified
    # `basilisp.lang...` modules don't result in compiler errors
    yield ast.Import(names=[ast.alias(name="basilisp", asname=None)])
    for imp in ctx.imports:
        name = imp.key.name
        alias = _MODULE_ALIASES.get(name, None)
        yield ast.Import(names=[ast.alias(name=name, asname=alias)])

Response:
Generate the Python Import AST node for importing all required
    language support modules.


Instruction:
Can you write a function in Python 3 where it
generates the Python From... Import AST node for importing language support modules.

Response:
def _from_module_import() -> ast.ImportFrom:
    """Generate the Python From ... Import AST node for importing
    language support modules."""
    return ast.ImportFrom(
        module="basilisp.lang.runtime",
        names=[ast.alias(name="Var", asname=_VAR_ALIAS)],
        level=0,
    )


Instruction:
Create a Python 3 function to
assign a Python variable named ns_var to the value of the current namespace.

Response:
def _ns_var(
    py_ns_var: str = _NS_VAR, lisp_ns_var: str = LISP_NS_VAR, lisp_ns_ns: str = CORE_NS
) -> ast.Assign:
    """Assign a Python variable named `ns_var` to the value of the current
    namespace."""
    return ast.Assign(
        targets=[ast.Name(id=py_ns_var, ctx=ast.Store())],
        value=ast.Call(
            func=_FIND_VAR_FN_NAME,
            args=[
                ast.Call(
                    func=_NEW_SYM_FN_NAME,
                    args=[ast.Str(lisp_ns_var)],
                    keywords=[ast.keyword(arg="ns", value=ast.Str(lisp_ns_ns))],
                )
            ],
            keywords=[],
        ),
    )


Instruction:
Given the following Python 3 function, write the documentation
def py_module_preamble(ctx: GeneratorContext,) -> GeneratedPyAST:
    preamble: List[ast.AST] = []
    preamble.extend(_module_imports(ctx))
    preamble.append(_from_module_import())
    preamble.append(_ns_var())
    return GeneratedPyAST(node=ast.NameConstant(None), dependencies=preamble)

Response: Bootstrap a new module with imports and other boilerplate.


Instruction:
How would you implement a function in Python 3 that
checks if a Var reference cannot be direct linked.

Response:
def warn_on_var_indirection(self) -> bool:
        """If True, warn when a Var reference cannot be direct linked (iff
        use_var_indirection is False).."""
        return not self.use_var_indirection and self._opts.entry(
            WARN_ON_VAR_INDIRECTION, True
        )


Instruction:
How would you explain what the following Python 3 function does
def set(members: Iterable[T], meta=None) -> Set[T]:  # pylint:disable=redefined-builtin
    return Set(pset(members), meta=meta)

Response: Creates a new set with the given members.


Instruction:
How would you explain what the following Python 3 function does
def s(*members: T, meta=None) -> Set[T]:
    return Set(pset(members), meta=meta)

Response: Creates a new set from members.


Instruction:
Make a summary of the following Python 3 code
def _filter_dead_code(nodes: Iterable[ast.AST]) -> List[ast.AST]:
    new_nodes: List[ast.AST] = []
    for node in nodes:
        if isinstance(node, (ast.Break, ast.Continue, ast.Return)):
            new_nodes.append(node)
            break
        new_nodes.append(node)
    return new_nodes

Response: Return a list of body nodes that are not unreachable code.


Instruction:
Explain what the following Python 3 code does
def visit_ExceptHandler(self, node: ast.ExceptHandler) -> Optional[ast.AST]:
        new_node = self.generic_visit(node)
        assert isinstance(new_node, ast.ExceptHandler)
        return ast.copy_location(
            ast.ExceptHandler(
                type=new_node.type,
                name=new_node.name,
                body=_filter_dead_code(new_node.body),
            ),
            new_node,
        )

Response: Eliminate dead code from except handler bodies.


Instruction:
Explain what the following Python 3 code does
def visit_Expr(self, node: ast.Expr) -> Optional[ast.Expr]:
        if isinstance(
            node.value,
            (
                ast.Constant,  # type: ignore
                ast.Name,
                ast.NameConstant,
                ast.Num,
                ast.Str,
            ),
        ):
            return None
        return node

Response:
Eliminate no - op constant expressions which are in the tree
        as standalone statements.


Instruction:
How would you explain what the following Python 3 function does
def visit_FunctionDef(self, node: ast.FunctionDef) -> Optional[ast.AST]:
        new_node = self.generic_visit(node)
        assert isinstance(new_node, ast.FunctionDef)
        return ast.copy_location(
            ast.FunctionDef(
                name=new_node.name,
                args=new_node.args,
                body=_filter_dead_code(new_node.body),
                decorator_list=new_node.decorator_list,
                returns=new_node.returns,
            ),
            new_node,
        )

Response: Eliminate dead code from function bodies.


Instruction:
How would you explain what the following Python 3 function does
def visit_If(self, node: ast.If) -> Optional[ast.AST]:
        new_node = self.generic_visit(node)
        assert isinstance(new_node, ast.If)
        return ast.copy_location(
            ast.If(
                test=new_node.test,
                body=_filter_dead_code(new_node.body),
                orelse=_filter_dead_code(new_node.orelse),
            ),
            new_node,
        )

Response: Eliminate dead code from if body.


Instruction:
How would you code a function in Python 3 to
eliminate dead code from while bodies.

Response:
def visit_While(self, node: ast.While) -> Optional[ast.AST]:
        """Eliminate dead code from while bodies."""
        new_node = self.generic_visit(node)
        assert isinstance(new_node, ast.While)
        return ast.copy_location(
            ast.While(
                test=new_node.test,
                body=_filter_dead_code(new_node.body),
                orelse=_filter_dead_code(new_node.orelse),
            ),
            new_node,
        )


Instruction:
Implement a Python 3 function for
eliminating dead code from except body.

Response:
def visit_Try(self, node: ast.Try) -> Optional[ast.AST]:
        """Eliminate dead code from except try bodies."""
        new_node = self.generic_visit(node)
        assert isinstance(new_node, ast.Try)
        return ast.copy_location(
            ast.Try(
                body=_filter_dead_code(new_node.body),
                handlers=new_node.handlers,
                orelse=_filter_dead_code(new_node.orelse),
                finalbody=_filter_dead_code(new_node.finalbody),
            ),
            new_node,
        )


Instruction:
Here you have a function in Python 3, explain what it does
def _new_module(name: str, doc=None) -> types.ModuleType:
    mod = types.ModuleType(name, doc=doc)
    mod.__loader__ = None
    mod.__package__ = None
    mod.__spec__ = None
    mod.__basilisp_bootstrapped__ = False  # type: ignore
    return mod

Response: Create a new empty Basilisp Python module.


Instruction:
Can you implement a function in Python 3 that
returns the first element of the sequence or None if o is None.

Response:
def first(o):
    """If o is a ISeq, return the first element from o. If o is None, return
    None. Otherwise, coerces o to a Seq and returns the first."""
    if o is None:
        return None
    if isinstance(o, ISeq):
        return o.first
    s = to_seq(o)
    if s is None:
        return None
    return s.first


Instruction:
Create a Python 3 function to
return the elements after the first in o.

Response:
def rest(o) -> Optional[ISeq]:
    """If o is a ISeq, return the elements after the first in o. If o is None,
    returns an empty seq. Otherwise, coerces o to a seq and returns the rest."""
    if o is None:
        return None
    if isinstance(o, ISeq):
        s = o.rest
        if s is None:
            return lseq.EMPTY
        return s
    n = to_seq(o)
    if n is None:
        return lseq.EMPTY
    return n.rest


Instruction:
Can you implement a function in Python 3 that
returns the nth rest sequence of coll.

Response:
def nthrest(coll, i: int):
    """Returns the nth rest sequence of coll, or coll if i is 0."""
    while True:
        if coll is None:
            return None
        if i == 0:
            return coll
        i -= 1
        coll = rest(coll)


Instruction:
Can you write a function in Python 3 where it
returns the nth next sequence of coll.

Response:
def nthnext(coll, i: int) -> Optional[ISeq]:
    """Returns the nth next sequence of coll."""
    while True:
        if coll is None:
            return None
        if i == 0:
            return to_seq(coll)
        i -= 1
        coll = next_(coll)


Instruction:
Here you have a function in Python 3, explain what it does
def cons(o, seq) -> ISeq:
    if seq is None:
        return llist.l(o)
    if isinstance(seq, ISeq):
        return seq.cons(o)
    return Maybe(to_seq(seq)).map(lambda s: s.cons(o)).or_else(lambda: llist.l(o))

Response: Creates a new sequence where o is the first element and seq is the rest.


Instruction:
Can you generate the documentation for the following Python 3 function
def to_seq(o) -> Optional[ISeq]:
    if o is None:
        return None
    if isinstance(o, ISeq):
        return _seq_or_nil(o)
    if isinstance(o, ISeqable):
        return _seq_or_nil(o.seq())
    return _seq_or_nil(lseq.sequence(o))

Response: Coerce the argument o to a ISeq.


Instruction:
Can you generate the documentation for the following Python 3 function
def concat(*seqs) -> ISeq:
    allseqs = lseq.sequence(itertools.chain(*filter(None, map(to_seq, seqs))))
    if allseqs is None:
        return lseq.EMPTY
    return allseqs

Response: Concatenate the sequences given by seqs into a single ISeq.


Instruction:
Can you tell what is the following Python 3 function doing
def apply(f, args):
    final = list(args[:-1])

    try:
        last = args[-1]
    except TypeError as e:
        logger.debug("Ignored %s: %s", type(e).__name__, e)

    s = to_seq(last)
    if s is not None:
        final.extend(s)

    return f(*final)

Response: Apply function f to the arguments provided.


Instruction:
Can you generate the documentation for the following Python 3 function
def apply_kw(f, args):
    final = list(args[:-1])

    try:
        last = args[-1]
    except TypeError as e:
        logger.debug("Ignored %s: %s", type(e).__name__, e)

    kwargs = to_py(last, lambda kw: munge(kw.name, allow_builtins=True))
    return f(*final, **kwargs)

Response: Apply function f to the arguments provided.


Instruction:
Here you have a function in Python 3, explain what it does
def nth(coll, i, notfound=__nth_sentinel):
    if coll is None:
        return None

    try:
        return coll[i]
    except IndexError as ex:
        if notfound is not __nth_sentinel:
            return notfound
        raise ex
    except TypeError as ex:
        # Log these at TRACE so they don't gum up the DEBUG logs since most
        # cases where this exception occurs are not bugs.
        logger.log(TRACE, "Ignored %s: %s", type(ex).__name__, ex)

    try:
        for j, e in enumerate(coll):
            if i == j:
                return e
        if notfound is not __nth_sentinel:
            return notfound
        raise IndexError(f"Index {i} out of bounds")
    except TypeError:
        pass

    raise TypeError(f"nth not supported on object of type {type(coll)}")

Response: Returns the ith element of coll.


Instruction:
Can you tell what is the following Python 3 function doing
def assoc(m, *kvs):
    if m is None:
        return lmap.Map.empty().assoc(*kvs)
    if isinstance(m, IAssociative):
        return m.assoc(*kvs)
    raise TypeError(
        f"Object of type {type(m)} does not implement Associative interface"
    )

Response: Associate keys to values in associative data structure m. Returns a new Map with key - values kvs.


Instruction:
Create a Python 3 function for
updating the value for key k in associative data structure m with the return value from calling f ( old_v new_v

Response:
def update(m, k, f, *args):
    """Updates the value for key k in associative data structure m with the return value from
    calling f(old_v, *args). If m is None, use an empty map. If k is not in m, old_v will be
    None."""
    if m is None:
        return lmap.Map.empty().assoc(k, f(None, *args))
    if isinstance(m, IAssociative):
        old_v = m.entry(k)
        new_v = f(old_v, *args)
        return m.assoc(k, new_v)
    raise TypeError(
        f"Object of type {type(m)} does not implement Associative interface"
    )


Instruction:
Can you create a Python 3 function that
conjoins xs to collection.

Response:
def conj(coll, *xs):
    """Conjoin xs to collection. New elements may be added in different positions
    depending on the type of coll. conj returns the same type as coll. If coll
    is None, return a list with xs conjoined."""
    if coll is None:
        l = llist.List.empty()
        return l.cons(*xs)
    if isinstance(coll, IPersistentCollection):
        return coll.cons(*xs)
    raise TypeError(
        f"Object of type {type(coll)} does not implement Collection interface"
    )


Instruction:
Given the following Python 3 function, write the documentation
def partial(f, *args):

    @functools.wraps(f)
    def partial_f(*inner_args):
        return f(*itertools.chain(args, inner_args))

    return partial_f

Response: Return a function which is the partial application of f with args.


Instruction:
How would you explain what the following Python 3 function does
def deref(o, timeout_s=None, timeout_val=None):
    if isinstance(o, IDeref):
        return o.deref()
    elif isinstance(o, IBlockingDeref):
        return o.deref(timeout_s, timeout_val)
    raise TypeError(f"Object of type {type(o)} cannot be dereferenced")

Response: Dereference a Deref object and return its contents.


Instruction:
Write a Python 3 script for
comparing two objects by value.

Response:
def equals(v1, v2) -> bool:
    """Compare two objects by value. Unlike the standard Python equality operator,
    this function does not consider 1 == True or 0 == False. All other equality
    operations are the same and performed using Python's equality operator."""
    if isinstance(v1, (bool, type(None))) or isinstance(v2, (bool, type(None))):
        return v1 is v2
    return v1 == v2


Instruction:
Write a Python 3 script for
returning a sorted sequence of the elements in coll using a comparator function f.

Response:
def sort(coll, f=None) -> Optional[ISeq]:
    """Return a sorted sequence of the elements in coll. If a comparator
    function f is provided, compare elements in coll using f."""
    return to_seq(sorted(coll, key=Maybe(f).map(functools.cmp_to_key).value))


Instruction:
Given the following Python 3 function, write the documentation
def contains(coll, k):
    if isinstance(coll, IAssociative):
        return coll.contains(k)
    return k in coll

Response: Return true if o contains the key k.


Instruction:
Can you write a function in Python 3 where it
returns the value of k in m. Return default if k not found in m.

Response:
def get(m, k, default=None):
    """Return the value of k in m. Return default if k not found in m."""
    if isinstance(m, IAssociative):
        return m.entry(k, default=default)

    try:
        return m[k]
    except (KeyError, IndexError, TypeError) as e:
        logger.debug("Ignored %s: %s", type(e).__name__, e)
        return default


Instruction:
Given the following Python 3 function, write the documentation
def to_py(o, keyword_fn: Callable[[kw.Keyword], Any] = _kw_name):
    if isinstance(o, ISeq):
        return _to_py_list(o, keyword_fn=keyword_fn)
    elif not isinstance(
        o, (IPersistentList, IPersistentMap, IPersistentSet, IPersistentVector)
    ):
        return o
    else:  # pragma: no cover
        return _to_py_backup(o, keyword_fn=keyword_fn)

Response: Recursively convert Lisp collections into Python collections.


Instruction:
Write a Python 3 function for
producing a string representation of an object.

Response:
def lrepr(o, human_readable: bool = False) -> str:
    """Produce a string representation of an object. If human_readable is False,
    the string representation of Lisp objects is something that can be read back
    in by the reader as the same object."""
    core_ns = Namespace.get(sym.symbol(CORE_NS))
    assert core_ns is not None
    return lobj.lrepr(
        o,
        human_readable=human_readable,
        print_dup=core_ns.find(sym.symbol(_PRINT_DUP_VAR_NAME)).value,  # type: ignore
        print_length=core_ns.find(  # type: ignore
            sym.symbol(_PRINT_LENGTH_VAR_NAME)
        ).value,
        print_level=core_ns.find(  # type: ignore
            sym.symbol(_PRINT_LEVEL_VAR_NAME)
        ).value,
        print_meta=core_ns.find(sym.symbol(_PRINT_META_VAR_NAME)).value,  # type: ignore
        print_readably=core_ns.find(  # type: ignore
            sym.symbol(_PRINT_READABLY_VAR_NAME)
        ).value,
    )


Instruction:
Create a Python 3 function to
collect Python starred arguments into a Basilisp list.

Response:
def _collect_args(args) -> ISeq:
    """Collect Python starred arguments into a Basilisp list."""
    if isinstance(args, tuple):
        return llist.list(args)
    raise TypeError("Python variadic arguments should always be a tuple")


Instruction:
Can you tell what is the following Python 3 function doing
def _trampoline(f):

    @functools.wraps(f)
    def trampoline(*args, **kwargs):
        while True:
            ret = f(*args, **kwargs)
            if isinstance(ret, _TrampolineArgs):
                args = ret.args
                kwargs = ret.kwargs
                continue
            return ret

    return trampoline

Response:
Trampoline a function repeatedly until it is finished recurring to help
    avoid stack growth.


Instruction:
Explain what the following Python 3 code does
def _fn_with_meta(f, meta: Optional[lmap.Map]):

    if not isinstance(meta, lmap.Map):
        raise TypeError("meta must be a map")

    if inspect.iscoroutinefunction(f):

        @functools.wraps(f)
        async def wrapped_f(*args, **kwargs):
            return await f(*args, **kwargs)

    else:

        @functools.wraps(f)  # type: ignore
        def wrapped_f(*args, **kwargs):
            return f(*args, **kwargs)

    wrapped_f.meta = (  # type: ignore
        f.meta.update(meta)
        if hasattr(f, "meta") and isinstance(f.meta, lmap.Map)
        else meta
    )
    wrapped_f.with_meta = partial(_fn_with_meta, wrapped_f)  # type: ignore
    return wrapped_f

Response: Return a new function with the given meta.


Instruction:
Given the following Python 3 function, write the documentation
def _basilisp_fn(f):
    assert not hasattr(f, "meta")
    f._basilisp_fn = True
    f.meta = None
    f.with_meta = partial(_fn_with_meta, f)
    return f

Response:
Create a Basilisp function setting meta and supplying a with_meta
    method implementation.


Instruction:
How would you explain what the following Python 3 function does
def init_ns_var(which_ns: str = CORE_NS, ns_var_name: str = NS_VAR_NAME) -> Var:
    core_sym = sym.Symbol(which_ns)
    core_ns = Namespace.get_or_create(core_sym)
    ns_var = Var.intern(core_sym, sym.Symbol(ns_var_name), core_ns, dynamic=True)
    logger.debug(f"Created namespace variable {sym.symbol(ns_var_name, ns=which_ns)}")
    return ns_var

Response: Initialize the dynamic * ns * variable in the Namespace which_ns.


Instruction:
Can you tell what is the following Python 3 function doing
def set_current_ns(
    ns_name: str,
    module: types.ModuleType = None,
    ns_var_name: str = NS_VAR_NAME,
    ns_var_ns: str = NS_VAR_NS,
) -> Var:
    """Set the value of the dynamic variable `*ns*` in the current thread."""
    symbol = sym.Symbol(ns_name)
    ns = Namespace.get_or_create(symbol, module=module)
    ns_var_sym = sym.Symbol(ns_var_name, ns=ns_var_ns)
    ns_var = Maybe(Var.find(ns_var_sym)).or_else_raise(
        lambda: RuntimeException(
            f"Dynamic Var {sym.Symbol(ns_var_name, ns=ns_var_ns)} not bound!"
        )
    )
    ns_var.push_bindings(ns)
    logger.debug(f"Setting {ns_var_sym} to {ns}")
    return ns_var

Response: Set the value of the dynamic variable ns_var_name in the current thread.


Instruction:
How would you explain what the following Python 3 function does
def get_current_ns(
    ns_var_name: str = NS_VAR_NAME, ns_var_ns: str = NS_VAR_NS
) -> Namespace:
    """Get the value of the dynamic variable `*ns*` in the current thread."""
    ns_sym = sym.Symbol(ns_var_name, ns=ns_var_ns)
    ns: Namespace = Maybe(Var.find(ns_sym)).map(lambda v: v.value).or_else_raise(
        lambda: RuntimeException(f"Dynamic Var {ns_sym} not bound!")
    )
    return ns

Response: Get the value of the dynamic variable ns in the current thread.


Instruction:
How would you implement a function in Python 3 that
resolves the aliased symbol in the current namespace.

Response:
def resolve_alias(s: sym.Symbol, ns: Optional[Namespace] = None) -> sym.Symbol:
    """Resolve the aliased symbol in the current namespace."""
    if s in _SPECIAL_FORMS:
        return s

    ns = Maybe(ns).or_else(get_current_ns)
    if s.ns is not None:
        aliased_ns = ns.get_alias(sym.symbol(s.ns))
        if aliased_ns is not None:
            return sym.symbol(s.name, aliased_ns.name)
        else:
            return s
    else:
        which_var = ns.find(sym.symbol(s.name))
        if which_var is not None:
            return sym.symbol(which_var.name.name, which_var.ns.name)
        else:
            return sym.symbol(s.name, ns=ns.name)


Instruction:
How would you code a function in Python 3 to
resolve the aliased symbol to a Var from the specified namespace or the current namespace.

Response:
def resolve_var(s: sym.Symbol, ns: Optional[Namespace] = None) -> Optional[Var]:
    """Resolve the aliased symbol to a Var from the specified
    namespace, or the current namespace if none is specified."""
    return Var.find(resolve_alias(s, ns))


Instruction:
How would you code a function in Python 3 to
add generated Python code to a dynamic variable in which_ns.

Response:
def add_generated_python(
    generated_python: str,
    var_name: str = _GENERATED_PYTHON_VAR_NAME,
    which_ns: Optional[str] = None,
) -> None:
    """Add generated Python code to a dynamic variable in which_ns."""
    if which_ns is None:
        which_ns = get_current_ns().name
    ns_sym = sym.Symbol(var_name, ns=which_ns)
    v = Maybe(Var.find(ns_sym)).or_else(
        lambda: Var.intern(
            sym.symbol(which_ns),  # type: ignore
            sym.symbol(var_name),
            "",
            dynamic=True,
            meta=lmap.map({_PRIVATE_META_KEY: True}),
        )
    )
    v.value = v.value + generated_python


Instruction:
Can you generate a brief explanation for the following Python 3 code
def print_generated_python(
    var_name: str = _PRINT_GENERATED_PY_VAR_NAME, core_ns_name: str = CORE_NS
) -> bool:
    """Return the value of the `*print-generated-python*` dynamic variable."""
    ns_sym = sym.Symbol(var_name, ns=core_ns_name)
    return (
        Maybe(Var.find(ns_sym))
        .map(lambda v: v.value)
        .or_else_raise(lambda: RuntimeException(f"Dynamic Var {ns_sym} not bound!"))
    )

Response: Return the value of the * print - generated - python * dynamic variable.


Instruction:
How would you explain what the following Python 3 function does
def bootstrap(ns_var_name: str = NS_VAR_NAME, core_ns_name: str = CORE_NS) -> None:
    core_ns_sym = sym.symbol(core_ns_name)
    ns_var_sym = sym.symbol(ns_var_name, ns=core_ns_name)
    __NS = Maybe(Var.find(ns_var_sym)).or_else_raise(
        lambda: RuntimeException(f"Dynamic Var {ns_var_sym} not bound!")
    )

    def in_ns(s: sym.Symbol):
        ns = Namespace.get_or_create(s)
        __NS.value = ns
        return ns

    Var.intern_unbound(core_ns_sym, sym.symbol("unquote"))
    Var.intern_unbound(core_ns_sym, sym.symbol("unquote-splicing"))
    Var.intern(
        core_ns_sym, sym.symbol("in-ns"), in_ns, meta=lmap.map({_REDEF_META_KEY: True})
    )
    Var.intern(
        core_ns_sym,
        sym.symbol(_PRINT_GENERATED_PY_VAR_NAME),
        False,
        dynamic=True,
        meta=lmap.map({_PRIVATE_META_KEY: True}),
    )
    Var.intern(
        core_ns_sym,
        sym.symbol(_GENERATED_PYTHON_VAR_NAME),
        "",
        dynamic=True,
        meta=lmap.map({_PRIVATE_META_KEY: True}),
    )

    # Dynamic Vars for controlling printing
    Var.intern(
        core_ns_sym, sym.symbol(_PRINT_DUP_VAR_NAME), lobj.PRINT_DUP, dynamic=True
    )
    Var.intern(
        core_ns_sym, sym.symbol(_PRINT_LENGTH_VAR_NAME), lobj.PRINT_LENGTH, dynamic=True
    )
    Var.intern(
        core_ns_sym, sym.symbol(_PRINT_LEVEL_VAR_NAME), lobj.PRINT_LEVEL, dynamic=True
    )
    Var.intern(
        core_ns_sym, sym.symbol(_PRINT_META_VAR_NAME), lobj.PRINT_META, dynamic=True
    )
    Var.intern(
        core_ns_sym,
        sym.symbol(_PRINT_READABLY_VAR_NAME),
        lobj.PRINT_READABLY,
        dynamic=True,
    )

Response: Bootstrap the environment with functions that are difficult to maintain the minimal lisp environment.


Instruction:
Can you implement a function in Python 3 that
interns the value bound to the symbol name in namespace ns.

Response:
def intern(
        ns: sym.Symbol, name: sym.Symbol, val, dynamic: bool = False, meta=None
    ) -> "Var":
        """Intern the value bound to the symbol `name` in namespace `ns`."""
        var_ns = Namespace.get_or_create(ns)
        var = var_ns.intern(name, Var(var_ns, name, dynamic=dynamic, meta=meta))
        var.root = val
        return var


Instruction:
Here you have a function in Python 3, explain what it does
def intern_unbound(
        ns: sym.Symbol, name: sym.Symbol, dynamic: bool = False, meta=None
    ) -> "Var":
        """Create a new unbound `Var` instance to the symbol `name` in namespace `ns`."""
        var_ns = Namespace.get_or_create(ns)
        return var_ns.intern(name, Var(var_ns, name, dynamic=dynamic, meta=meta))

Response: Create a new unbound Var instance to the symbol name in namespace ns.


Instruction:
How would you explain what the following Python 3 function does
def find_in_ns(ns_sym: sym.Symbol, name_sym: sym.Symbol) -> "Optional[Var]":
        ns = Namespace.get(ns_sym)
        if ns:
            return ns.find(name_sym)
        return None

Response:
Return the value current bound to the name name_sym in the namespace
        specified by ns_sym.


Instruction:
Write a Python 3 script to
return the value currently bound to the name in the namespace specified by ns_qualified_sym.

Response:
def find(ns_qualified_sym: sym.Symbol) -> "Optional[Var]":
        """Return the value currently bound to the name in the namespace specified
        by `ns_qualified_sym`."""
        ns = Maybe(ns_qualified_sym.ns).or_else_raise(
            lambda: ValueError(
                f"Namespace must be specified in Symbol {ns_qualified_sym}"
            )
        )
        ns_sym = sym.symbol(ns)
        name_sym = sym.symbol(ns_qualified_sym.name)
        return Var.find_in_ns(ns_sym, name_sym)


Instruction:
How would you code a function in Python 3 to
find the Var currently bound to the specified symbol.

Response:
def find_safe(ns_qualified_sym: sym.Symbol) -> "Var":
        """Return the Var currently bound to the name in the namespace specified
        by `ns_qualified_sym`. If no Var is bound to that name, raise an exception.

        This is a utility method to return useful debugging information when code
        refers to an invalid symbol at runtime."""
        v = Var.find(ns_qualified_sym)
        if v is None:
            raise RuntimeException(
                f"Unable to resolve symbol {ns_qualified_sym} in this context"
            )
        return v


Instruction:
Given the following Python 3 function, write the documentation
def add_default_import(cls, module: str):
        if module in cls.GATED_IMPORTS:
            cls.DEFAULT_IMPORTS.swap(lambda s: s.cons(sym.symbol(module)))

Response: Add a gated default import to the default imports.


Instruction:
Can you tell what is the following Python 3 function doing
def add_alias(self, alias: sym.Symbol, namespace: "Namespace") -> None:
        self._aliases.swap(lambda m: m.assoc(alias, namespace))

Response: Add an alias for the given Namespace.


Instruction:
Can you generate the documentation for the following Python 3 function
def intern(self, sym: sym.Symbol, var: Var, force: bool = False) -> Var:
        m: lmap.Map = self._interns.swap(Namespace._intern, sym, var, force=force)
        return m.entry(sym)

Response: Intern the Var given in this namespace.


Instruction:
Create a Python 3 function for
swapping function used by intern to atomically intern a new variable in the symbol mapping for this Namespace.

Response:
def _intern(
        m: lmap.Map, sym: sym.Symbol, new_var: Var, force: bool = False
    ) -> lmap.Map:
        """Swap function used by intern to atomically intern a new variable in
        the symbol mapping for this Namespace."""
        var = m.entry(sym, None)
        if var is None or force:
            return m.assoc(sym, new_var)
        return m


Instruction:
Write a Python 3 script for
finding the Vars mapped by the given Symbol input or None if no Vars are mapped by that Symbol.

Response:
def find(self, sym: sym.Symbol) -> Optional[Var]:
        """Find Vars mapped by the given Symbol input or None if no Vars are
        mapped by that Symbol."""
        v = self.interns.entry(sym, None)
        if v is None:
            return self.refers.entry(sym, None)
        return v


Instruction:
Can you write a function in Python 3 where it
adds the Symbol as an imported Symbol in this Namespace.

Response:
def add_import(
        self, sym: sym.Symbol, module: types.ModuleType, *aliases: sym.Symbol
    ) -> None:
        """Add the Symbol as an imported Symbol in this Namespace. If aliases are given,
        the aliases will be applied to the """
        self._imports.swap(lambda m: m.assoc(sym, module))
        if aliases:
            self._import_aliases.swap(
                lambda m: m.assoc(
                    *itertools.chain.from_iterable([(alias, sym) for alias in aliases])
                )
            )


Instruction:
Create a Python 3 function for
returning the module that has been imported into this Namespace or None if no module has been imported into this Namespace.

Response:
def get_import(self, sym: sym.Symbol) -> Optional[types.ModuleType]:
        """Return the module if a moduled named by sym has been imported into
        this Namespace, None otherwise.

        First try to resolve a module directly with the given name. If no module
        can be resolved, attempt to resolve the module using import aliases."""
        mod = self.imports.entry(sym, None)
        if mod is None:
            alias = self.import_aliases.get(sym, None)
            if alias is None:
                return None
            return self.imports.entry(alias, None)
        return mod


Instruction:
Given the following Python 3 function, write the documentation
def add_refer(self, sym: sym.Symbol, var: Var) -> None:
        if not var.is_private:
            self._refers.swap(lambda s: s.assoc(sym, var))

Response: Add a reference to the given variable.


Instruction:
Write a Python 3 function that can
get the Var referred by a Symbol or None if it does not exist.

Response:
def get_refer(self, sym: sym.Symbol) -> Optional[Var]:
        """Get the Var referred by Symbol or None if it does not exist."""
        return self.refers.entry(sym, None)


Instruction:
Implement a function in Python 3 to
refer all _public_ interns from another namespace.

Response:
def __refer_all(cls, refers: lmap.Map, other_ns_interns: lmap.Map) -> lmap.Map:
        """Refer all _public_ interns from another namespace."""
        final_refers = refers
        for entry in other_ns_interns:
            s: sym.Symbol = entry.key
            var: Var = entry.value
            if not var.is_private:
                final_refers = final_refers.assoc(s, var)
        return final_refers


Instruction:
Can you implement a function in Python 3 that
refers all the Vars in the other namespace.

Response:
def refer_all(self, other_ns: "Namespace"):
        """Refer all the Vars in the other namespace."""
        self._refers.swap(Namespace.__refer_all, other_ns.interns)


Instruction:
Here you have a function in Python 3, explain what it does
def __get_or_create(
        ns_cache: NamespaceMap,
        name: sym.Symbol,
        module: types.ModuleType = None,
        core_ns_name=CORE_NS,
    ) -> lmap.Map:
        """Private swap function used by `get_or_create` to atomically swap
        the new namespace map into the global cache."""
        ns = ns_cache.entry(name, None)
        if ns is not None:
            return ns_cache
        new_ns = Namespace(name, module=module)
        if name.name != core_ns_name:
            core_ns = ns_cache.entry(sym.symbol(core_ns_name), None)
            assert core_ns is not None, "Core namespace not loaded yet!"
            new_ns.refer_all(core_ns)
        return ns_cache.assoc(name, new_ns)

Response:
Private function used by get_or_create to atomically swap
        the new namespace map into the global cache.


Instruction:
Can you tell what is the following Python 3 function doing
def get_or_create(
        cls, name: sym.Symbol, module: types.ModuleType = None
    ) -> "Namespace":
        """Get the namespace bound to the symbol `name` in the global namespace
        cache, creating it if it does not exist.
        Return the namespace."""
        return cls._NAMESPACES.swap(Namespace.__get_or_create, name, module=module)[
            name
        ]

Response:
Get the namespace bound to the symbol name in the global namespace
        cache creating it if it does not exist.


Instruction:
Can you write a function in Python 3 where it
gets the namespace bound to the symbol name.

Response:
def get(cls, name: sym.Symbol) -> "Optional[Namespace]":
        """Get the namespace bound to the symbol `name` in the global namespace
        cache. Return the namespace if it exists or None otherwise.."""
        return cls._NAMESPACES.deref().entry(name, None)


Instruction:
Explain what the following Python 3 code does
def remove(cls, name: sym.Symbol) -> Optional["Namespace"]:
        while True:
            oldval: lmap.Map = cls._NAMESPACES.deref()
            ns: Optional[Namespace] = oldval.entry(name, None)
            newval = oldval
            if ns is not None:
                newval = oldval.dissoc(name)
            if cls._NAMESPACES.compare_and_set(oldval, newval):
                return ns

Response: Remove the namespace bound to the symbol name in the global cache and return that namespace. Return None if the symbol does not exist in the global cache.


Instruction:
Here you have a function in Python 3, explain what it does
def __completion_matcher(text: str) -> CompletionMatcher:

        def is_match(entry: Tuple[sym.Symbol, Any]) -> bool:
            return entry[0].name.startswith(text)

        return is_match

Response:
Return a function which matches any symbol keys from map entries
        against the given text.


Instruction:
Can you implement a function in Python 3 that
returns an iterable of possible completions matching the given prefix from the list of aliased namespaces.

Response:
def __complete_alias(
        self, prefix: str, name_in_ns: Optional[str] = None
    ) -> Iterable[str]:
        """Return an iterable of possible completions matching the given
        prefix from the list of aliased namespaces. If name_in_ns is given,
        further attempt to refine the list to matching names in that namespace."""
        candidates = filter(
            Namespace.__completion_matcher(prefix), [(s, n) for s, n in self.aliases]
        )
        if name_in_ns is not None:
            for _, candidate_ns in candidates:
                for match in candidate_ns.__complete_interns(
                    name_in_ns, include_private_vars=False
                ):
                    yield f"{prefix}/{match}"
        else:
            for alias, _ in candidates:
                yield f"{alias}/"


Instruction:
Implement a Python 3 function for
returning an iterable of possible completions matching the given prefix from the list of imports and aliased imports.

Response:
def __complete_imports_and_aliases(
        self, prefix: str, name_in_module: Optional[str] = None
    ) -> Iterable[str]:
        """Return an iterable of possible completions matching the given
        prefix from the list of imports and aliased imports. If name_in_module
        is given, further attempt to refine the list to matching names in that
        namespace."""
        imports = self.imports
        aliases = lmap.map(
            {
                alias: imports.entry(import_name)
                for alias, import_name in self.import_aliases
            }
        )

        candidates = filter(
            Namespace.__completion_matcher(prefix), itertools.chain(aliases, imports)
        )
        if name_in_module is not None:
            for _, module in candidates:
                for name in module.__dict__:
                    if name.startswith(name_in_module):
                        yield f"{prefix}/{name}"
        else:
            for candidate_name, _ in candidates:
                yield f"{candidate_name}/"


Instruction:
Can you generate the documentation for the following Python 3 function
def __complete_interns(
        self, value: str, include_private_vars: bool = True
    ) -> Iterable[str]:
        """Return an iterable of possible completions matching the given
        prefix from the list of interned Vars."""
        if include_private_vars:
            is_match = Namespace.__completion_matcher(value)
        else:
            _is_match = Namespace.__completion_matcher(value)

            def is_match(entry: Tuple[sym.Symbol, Var]) -> bool:
                return _is_match(entry) and not entry[1].is_private

        return map(
            lambda entry: f"{entry[0].name}",
            filter(is_match, [(s, v) for s, v in self.interns]),
        )

Response:
Return an iterable of possible completions matching the given
        prefix from the list of interned Vars.


Instruction:
Can you tell what is the following Python 3 function doing
def __complete_refers(self, value: str) -> Iterable[str]:
        return map(
            lambda entry: f"{entry[0].name}",
            filter(
                Namespace.__completion_matcher(value), [(s, v) for s, v in self.refers]
            ),
        )

Response:
Return an iterable of possible completions matching the given
        prefix from the list of referred Vars.


Instruction:
Implement a function in Python 3 to
return an iterable of possible completions for the given text in this namespace.

Response:
def complete(self, text: str) -> Iterable[str]:
        """Return an iterable of possible completions for the given text in
        this namespace."""
        assert not text.startswith(":")

        if "/" in text:
            prefix, suffix = text.split("/", maxsplit=1)
            results = itertools.chain(
                self.__complete_alias(prefix, name_in_ns=suffix),
                self.__complete_imports_and_aliases(prefix, name_in_module=suffix),
            )
        else:
            results = itertools.chain(
                self.__complete_alias(text),
                self.__complete_imports_and_aliases(text),
                self.__complete_interns(text),
                self.__complete_refers(text),
            )

        return results


Instruction:
Write a Python 3 function for
returning the arguments for a trampolined function.

Response:
def args(self) -> Tuple:
        """Return the arguments for a trampolined function. If the function
        that is being trampolined has varargs, unroll the final argument if
        it is a sequence."""
        if not self._has_varargs:
            return self._args

        try:
            final = self._args[-1]
            if isinstance(final, ISeq):
                inits = self._args[:-1]
                return tuple(itertools.chain(inits, final))
            return self._args
        except IndexError:
            return ()


Instruction:
Can you write a function in Python 3 where it
creates a new list with the given members.

Response:
def list(members, meta=None) -> List:  # pylint:disable=redefined-builtin
    """Creates a new list."""
    return List(  # pylint: disable=abstract-class-instantiated
        plist(iterable=members), meta=meta
    )


Instruction:
Write a Python 3 script for
creating a new list from members.

Response:
def l(*members, meta=None) -> List:
    """Creates a new list from members."""
    return List(  # pylint: disable=abstract-class-instantiated
        plist(iterable=members), meta=meta
    )


Instruction:
How would you code a function in Python 3 to
return a function that changes the style of the key value

Response:
def change_style(style, representer):
    """
    This function is used to format the key value as a multi-line string maintaining the line breaks
    """

    def new_representer(dumper, data):
        scalar = representer(dumper, data)
        scalar.style = style
        return scalar

    return new_representer


Instruction:
Can you tell what is the following Python 3 function doing
def get_public_key(platform, service, purpose, key_use, version, public_key, keys_folder):
    '''
    Loads a public key from the file system and adds it to a dict of keys
    :param keys: A dict of keys
    :param platform the platform the key is for
    :param service the service the key is for
    :param key_use what the key is used for
    :param version the version of the key
    :param purpose: The purpose of the public key
    :param public_key: The name of the public key to add
    :param keys_folder: The location on disk where the key exists
    :param kid_override: This allows the caller to override the generated KID value
    :return: None
    '''
    public_key_data = get_file_contents(keys_folder, public_key)

    pub_key = load_pem_public_key(public_key_data.encode(), backend=backend)
    pub_bytes = pub_key.public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo)

    kid = _generate_kid_from_key(pub_bytes.decode())

    key = _create_key(platform=platform, service=service, key_use=key_use,
                      key_type="public", purpose=purpose, version=version,
                      public_key=public_key_data)
    return kid, key

Response: Loads a public key from the file system and adds it to a dict of keys


Instruction:
Given the following Python 3 function, write the documentation
def get_private_key(platform, service, purpose, key_use, version, private_key, keys_folder):
    '''
    Loads a private key from the file system and adds it to a dict of keys
    :param keys: A dict of keys
    :param platform the platform the key is for
    :param service the service the key is for
    :param key_use what the key is used for
    :param version the version of the key
    :param purpose: The purpose of the private key
    :param private_key: The name of the private key to add
    :param keys_folder: The location on disk where the key exists
    :param kid_override: This allows the caller to override the generated KID value
    :return: None
    '''
    private_key_data = get_file_contents(keys_folder, private_key)

    private_key = load_pem_private_key(private_key_data.encode(), None, backend=backend)

    pub_key = private_key.public_key()

    pub_bytes = pub_key.public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo)

    kid = _generate_kid_from_key(pub_bytes.decode())

    key = _create_key(platform=platform, service=service, key_use=key_use,
                      key_type="private", purpose=purpose, version=version,
                      public_key=pub_bytes.decode(), private_key=private_key_data)
    return kid, key

Response: Loads a private key from the file system and adds it to a dict of keys


Instruction:
Given the following Python 3 function, write the documentation
def get_key_for_purpose_and_type(self, purpose, key_type):
        key = [key for key in self.keys.values() if key.purpose == purpose and key.key_type == key_type]
        try:
            return key[0]
        except IndexError:
            return None

Response: Gets a key object that matches the purpose and key_type


Instruction:
Make a summary of the following Python 3 code
def get_default_args(func):
    args, _, _, defaults, *rest = inspect.getfullargspec(func)
    return dict(zip(reversed(args), reversed(defaults)))

Response: returns a dictionary of arg_name = > default_values for the input function


Instruction:
Implement a Python 3 function for
mapping the kwargs to objects in the order they were requested.

Response:
def map_arguments_to_objects(kwargs, objects, object_key, object_tuple_key, argument_key, result_value, default_result):
    """
    :param kwargs: kwargs used to call the multiget function
    :param objects: objects returned from the inner function
    :param object_key: field or set of fields that map to the kwargs provided
    :param object_tuple_key: A temporary shortcut until we allow dot.path traversal for object_key.
    Will call getattr(getattr(result, join_table_name), object_key)
    :param argument_key: field or set of fields that map to the objects provided
    :param result_value: Limit the fields returned to this field or set of fields (none = whole object)
    :param default_result: If the inner function returned none for a set of parameters, default to this
    :return:
    """

    # Map each object to the set of desired result data using a key
    # that corresponds to the parameters for ordering purposes
    map_ = map_objects_to_result(objects, object_key, object_tuple_key, result_value, default_result)
    element_count = get_request_count(kwargs)
    # Using the map we just made, return the objects in the same order
    # they were primed using the object and argument keys to match against
    return [map_[get_argument_key(kwargs, argument_key, index)] for index in range(0, element_count)]


Instruction:
Here you have a function in Python 3, explain what it does
def delete(self, *args):
        cache = get_cache()
        key = self.get_cache_key(*args)
        if key in cache:
            del cache[key]

Response: Remove the key from the request cache and from memcache.


Instruction:
Can you write a function in Python 3 where it
returns the current version and module in - dot - notation which is used by target parameters.

Response:
def get_dot_target_name(version=None, module=None):
  """Returns the current version/module in -dot- notation which is used by `target:` parameters."""
  version = version or get_current_version_name()
  module = module or get_current_module_name()
  return '-dot-'.join((version, module))


Instruction:
Given the following Python 3 function, write the documentation
def get_dot_target_name_safe(version=None, module=None):
  version = version or get_current_version_name_safe()
  module = module or get_current_module_name_safe()
  if version and module:
    return '-dot-'.join((version, module))
  return None

Response: Returns the current version and module in - dot - notation which is used by target parameters.


Instruction:
Create a Python 3 function to
return a dictionary of key - value pairs from os. environ.

Response:
def _get_os_environ_dict(keys):
  """Return a dictionary of key/values from os.environ."""
  return {k: os.environ.get(k, _UNDEFINED) for k in keys}


Instruction:
Can you write a function in Python 3 where it
connects to LASAF through a CAM - socket.

Response:
async def connect(self):
        """Connect to LASAF through a CAM-socket."""
        self.reader, self.writer = await asyncio.open_connection(
            self.host, self.port, loop=self.loop)
        self.welcome_msg = await self.reader.read(self.buffer_size)


Instruction:
Make a summary of the following Python 3 code
async def send(self, commands):
        msg = self._prepare_send(commands)
        self.writer.write(msg)
        await self.writer.drain()

Response: Send commands to LASAF through CAM - socket.


Instruction:
Make a summary of the following Python 3 code
async def receive(self):
        try:
            incomming = await self.reader.read(self.buffer_size)
        except OSError:
            return []

        return _parse_receive(incomming)

Response: Receive a message from the socket interface as list of OrderedDict.


Instruction:
Can you write a function in Python 3 where it
waits until command is received.

Response:
async def wait_for(self, cmd, value=None, timeout=60):
        """Hang until command is received.

        If value is supplied, it will hang until ``cmd:value`` is received.

        Parameters
        ----------
        cmd : string
            Command to wait for in bytestring from microscope CAM interface. If
            ``value`` is falsey, value of received command does not matter.
        value : string
            Wait until ``cmd:value`` is received.
        timeout : int
            Minutes to wait for command. If timeout is reached, an empty
            OrderedDict will be returned.

        Returns
        -------
        collections.OrderedDict
            Last received messsage or empty message if timeout is reached.

        """
        try:
            async with async_timeout(timeout * 60):
                while True:
                    msgs = await self.receive()
                    msg = check_messages(msgs, cmd, value=value)
                    if msg:
                        return msg
        except asyncio.TimeoutError:
            return OrderedDict()


Instruction:
Make a summary of the following Python 3 code
def close(self):
        if self.writer.can_write_eof():
            self.writer.write_eof()
        self.writer.close()

Response: Close the underlying file.


Instruction:
Here you have a function in Python 3, explain what it does
def lazyload(reference: str, *args, **kw):

	assert check_argument_types()

	def lazily_load_reference(self):
		ref = reference

		if ref.startswith('.'):
			ref = traverse(self, ref[1:])

		return load(ref, *args, **kw)

	return lazy(lazily_load_reference)

Response: Lazy load and cache an object reference upon dereferencing.


Instruction:
Implement a Python 3 function for
iterating through the FIQL string and yield a tuple containing the next set of entries.

Response:
def iter_parse(fiql_str):
    """Iterate through the FIQL string. Yield a tuple containing the
    following FIQL components for each iteration:

      - preamble: Any operator or opening/closing paranthesis preceding a
        constraint or at the very end of the FIQL string.
      - selector: The selector portion of a FIQL constraint or ``None`` if
        yielding the last portion of the string.
      - comparison: The comparison portion of a FIQL constraint or ``None``
        if yielding the last portion of the string.
      - argument: The argument portion of a FIQL constraint or ``None`` if
        yielding the last portion of the string.

    For usage see :func:`parse_str_to_expression`.

    Args:
        fiql_str (string): The FIQL formatted string we want to parse.

    Yields:
        tuple: Preamble, selector, comparison, argument.
    """
    while len(fiql_str):
        constraint_match = CONSTRAINT_COMP.split(fiql_str, 1)
        if len(constraint_match) < 2:
            yield (constraint_match[0], None, None, None)
            break
        yield (
            constraint_match[0],
            unquote_plus(constraint_match[1]),
            constraint_match[4],
            unquote_plus(constraint_match[6]) \
                    if constraint_match[6] else None
        )
        fiql_str = constraint_match[8]


Instruction:
Here you have a function in Python 3, explain what it does
def parse_str_to_expression(fiql_str):
    #pylint: disable=too-many-branches
    nesting_lvl = 0
    last_element = None
    expression = Expression()
    for (preamble, selector, comparison, argument) in iter_parse(fiql_str):
        if preamble:
            for char in preamble:
                if char == '(':
                    if isinstance(last_element, BaseExpression):
                        raise FiqlFormatException(
                            "%s can not be followed by %s" % (
                                last_element.__class__, Expression))
                    expression = expression.create_nested_expression()
                    nesting_lvl += 1
                elif char == ')':
                    expression = expression.get_parent()
                    last_element = expression
                    nesting_lvl -= 1
                else:
                    if not expression.has_constraint():
                        raise FiqlFormatException(
                            "%s proceeding initial %s" % (
                                Operator, Constraint))
                    if isinstance(last_element, Operator):
                        raise FiqlFormatException(
                            "%s can not be followed by %s" % (
                                Operator, Operator))
                    last_element = Operator(char)
                    expression = expression.add_operator(last_element)
        if selector:
            if isinstance(last_element, BaseExpression):
                raise FiqlFormatException("%s can not be followed by %s" % (
                    last_element.__class__, Constraint))
            last_element = Constraint(selector, comparison, argument)
            expression.add_element(last_element)
    if nesting_lvl != 0:
        raise FiqlFormatException(
            "At least one nested expression was not correctly closed")
    if not expression.has_constraint():
        raise FiqlFormatException(
            "Parsed string '%s' contained no constraint" % fiql_str)
    return expression

Response: Parses a FIQL formatted string into an Expression object.


Instruction:
How would you code a function in Python 3 to
encode objects like ndb. Model which have a. to_dict method.

Response:
def encode_model(obj):
  """Encode objects like ndb.Model which have a `.to_dict()` method."""
  obj_dict = obj.to_dict()
  for key, val in obj_dict.iteritems():
    if isinstance(val, types.StringType):
      try:
        unicode(val)
      except UnicodeDecodeError:
        # Encode binary strings (blobs) to base64.
        obj_dict[key] = base64.b64encode(val)
  return obj_dict


Instruction:
Here you have a function in Python 3, explain what it does
def dump(ndb_model, fp, **kwargs):
  for chunk in NdbEncoder(**kwargs).iterencode(ndb_model):
    fp.write(chunk)

Response: Custom json dump using the custom encoder above.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def object_hook_handler(self, val):
    return {k: self.decode_date(v) for k, v in val.iteritems()}

Response: Handles decoding of nested date strings.


Instruction:
Write a Python 3 script to
try to decode a string that looks like dates into datetime objects.

Response:
def decode_date(self, val):
    """Tries to decode strings that look like dates into datetime objects."""
    if isinstance(val, basestring) and val.count('-') == 2 and len(val) > 9:
      try:
        dt = dateutil.parser.parse(val)
        # Check for UTC.
        if val.endswith(('+00:00', '-00:00', 'Z')):
          # Then remove tzinfo for gae, which is offset-naive.
          dt = dt.replace(tzinfo=None)
        return dt
      except (TypeError, ValueError):
        pass
    return val


Instruction:
Explain what the following Python 3 code does
def decode(self, val):
    # First try the date decoder.
    new_val = self.decode_date(val)
    if val != new_val:
      return new_val
    # Fall back to the default decoder.
    return json.JSONDecoder.decode(self, val)

Response: Override of the default decode method that also uses decode_date.


Instruction:
Can you write a function in Python 3 where it
overrides the default JSONEncoder. default for NDB support.

Response:
def default(self, obj):
    """Overriding the default JSONEncoder.default for NDB support."""
    obj_type = type(obj)
    # NDB Models return a repr to calls from type().
    if obj_type not in self._ndb_type_encoding:
      if hasattr(obj, '__metaclass__'):
        obj_type = obj.__metaclass__
      else:
        # Try to encode subclasses of types
        for ndb_type in NDB_TYPES:
          if isinstance(obj, ndb_type):
            obj_type = ndb_type
            break

    fn = self._ndb_type_encoding.get(obj_type)

    if fn:
      return fn(obj)

    return json.JSONEncoder.default(self, obj)


Instruction:
Create a Python 3 function to
traverse down an object using getattr or getitem.

Response:
def traverse(obj, target:str, default=nodefault, executable:bool=False, separator:str='.', protect:bool=True):
	"""Traverse down an object, using getattr or getitem.

	If ``executable`` is ``True`` any executable function encountered will be, with no arguments. Traversal will
	continue on the result of that call.  You can change the separator as desired, i.e. to a '/'.

	By default attributes (but not array elements) prefixed with an underscore are taboo.  They will not resolve,
	raising a LookupError.

	Certain allowances are made: if a 'path segment' is numerical, it's treated as an array index. If attribute
	lookup fails, it will re-try on that object using array notation and continue from there.  This makes lookup
	very flexible.
	"""

	# TODO: Support numerical slicing, i.e. ``1:4``, or even just ``:-1`` and things.
	assert check_argument_types()

	value = obj
	remainder = target

	if not target:
		return obj

	while separator:
		name, separator, remainder = remainder.partition(separator)
		numeric = name.lstrip('-').isdigit()

		try:
			if numeric or (protect and name.startswith('_')):
				raise AttributeError()

			value = getattr(value, name)

			if executable and callable(value):
				value = value()

		except AttributeError:
			try:
				value = value[int(name) if numeric else name]

			except (KeyError, TypeError):
				if default is nodefault:
					raise LookupError("Could not resolve '" + target + "' on: " + repr(obj))

				return default

	return value


Instruction:
Can you tell what is the following Python 3 function doing
def load(target:str, namespace:str=None, default=nodefault, executable:bool=False, separators:Sequence[str]=('.', ':'),
		protect:bool=True):
	"""This helper function loads an object identified by a dotted-notation string.

	For example::

		# Load class Foo from example.objects
		load('example.objects:Foo')

		# Load the result of the class method ``new`` of the Foo object
		load('example.objects:Foo.new', executable=True)

	If a plugin namespace is provided simple name references are allowed.  For example::

		# Load the plugin named 'routing' from the 'web.dispatch' namespace
		load('routing', 'web.dispatch')

	The ``executable``, ``protect``, and first tuple element of ``separators`` are passed to the traverse function.
	Providing a namespace does not prevent full object lookup (dot-colon notation) from working.
	"""

	assert check_argument_types()

	if namespace and ':' not in target:
		allowable = dict((i.name,  i) for i in iter_entry_points(namespace))

		if target not in allowable:
			raise LookupError('Unknown plugin "' + target + '"; found: ' + ', '.join(allowable))

		return allowable[target].load()

	parts, _, target = target.partition(separators[1])

	try:
		obj = __import__(parts)
	except ImportError:
		if default is not nodefault:
			return default

		raise

	return traverse(
			obj,
			separators[0].join(parts.split(separators[0])[1:] + target.split(separators[0])),
			default = default,
			executable = executable,
			protect = protect
		) if target else obj

Response: This helper function loads an object identified by a dotted - notation string.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def validate_version():
    import leicacam
    version_string = leicacam.__version__
    versions = version_string.split('.', 3)
    try:
        for ver in versions:
            int(ver)
    except ValueError:
        print(
            'Only integers are allowed in release version, '
            'please adjust current version {}'.format(version_string))
        return None
    return version_string

Response: Validate version before release.


Instruction:
How would you code a function in Python 3 to
generate a new empty version of the current project.

Response:
def generate():
    """Generate changelog."""
    old_dir = os.getcwd()
    proj_dir = os.path.join(os.path.dirname(__file__), os.pardir)
    os.chdir(proj_dir)
    version = validate_version()
    if not version:
        os.chdir(old_dir)
        return
    print('Generating changelog for version {}'.format(version))
    options = [
        '--user', 'arve0', '--project', 'leicacam', '-v', '--with-unreleased',
        '--future-release', version]
    generator = ChangelogGenerator(options)
    generator.run()
    os.chdir(old_dir)


Instruction:
Can you implement a function in Python 3 that
finds strongly connected components in a graph using Tarjan s algorithm.

Response:
def strongly_connected_components(graph: Graph) -> List:
	"""Find the strongly connected components in a graph using Tarjan's algorithm.

	The `graph` argument should be a dictionary mapping node names to sequences of successor nodes.
	"""

	assert check_argument_types()

	result = []
	stack = []
	low = {}

	def visit(node: str):
		if node in low: return

		num = len(low)
		low[node] = num
		stack_pos = len(stack)
		stack.append(node)

		for successor in graph[node]:
			visit(successor)
			low[node] = min(low[node], low[successor])

		if num == low[node]:
			component = tuple(stack[stack_pos:])
			del stack[stack_pos:]

			result.append(component)

			for item in component:
				low[item] = len(graph)

	for node in graph:
		visit(node)

	return result


Instruction:
Given the following Python 3 function, write the documentation
def robust_topological_sort(graph: Graph) -> list:

	assert check_argument_types()

	components = strongly_connected_components(graph)

	node_component = {}
	for component in components:
		for node in component:
			node_component[node] = component

	component_graph = {}
	for component in components:
		component_graph[component] = []

	for node in graph:
		node_c = node_component[node]
		for successor in graph[node]:
			successor_c = node_component[successor]
			if node_c != successor_c:
				component_graph[node_c].append(successor_c)

	return topological_sort(component_graph)

Response: Perform a robust topological sort of the components in a graph.


Instruction:
Write a Python 3 script for
setting the parent expression for this object.

Response:
def set_parent(self, parent):
        """Set parent ``Expression`` for this object.

        Args:
            parent (Expression): The ``Expression`` which contains this object.

        Raises:
            FiqlObjectException: Parent must be of type ``Expression``.
        """
        if not isinstance(parent, Expression):
            raise FiqlObjectException("Parent must be of %s not %s" % (
                Expression, type(parent)))
        self.parent = parent


Instruction:
Can you implement a function in Python 3 that
gets the parent Expression for this object.

Response:
def get_parent(self):
        """Get the parent ``Expression`` for this object.

        Returns:
            Expression: The ``Expression`` which contains this object.

        Raises:
            FiqlObjectException: Parent is ``None``.
        """
        if not isinstance(self.parent, Expression):
            raise FiqlObjectException("Parent must be of %s not %s" % (
                Expression, type(self.parent)))
        return self.parent


Instruction:
Write a Python 3 script to
add an operator to the internal list of the current FiqlObject.

Response:
def add_operator(self, operator):
        """Add an ``Operator`` to the ``Expression``.

        The ``Operator`` may result in a new ``Expression`` if an ``Operator``
        already exists and is of a different precedence.

        There are three possibilities when adding an ``Operator`` to an
        ``Expression`` depending on whether or not an ``Operator`` already
        exists:

          - No ``Operator`` on the working ``Expression``; Simply set the
            ``Operator`` and return ``self``.
          - ``Operator`` already exists and is higher in precedence; The
            ``Operator`` and last ``Constraint`` belong in a sub-expression of
            the working ``Expression``.
          - ``Operator`` already exists and is lower in precedence; The
            ``Operator`` belongs to the parent of the working ``Expression``
            whether one currently exists or not. To remain in the context of
            the top ``Expression``, this method will return the parent here
            rather than ``self``.

        Args:
            operator (Operator): What we are adding.

        Returns:
            Expression: ``self`` or related ``Expression``.

        Raises:
            FiqlObjectExpression: Operator is not a valid ``Operator``.
        """
        if not isinstance(operator, Operator):
            raise FiqlObjectException("%s is not a valid element type" % (
                operator.__class__))

        if not self._working_fragment.operator:
            self._working_fragment.operator = operator
        elif operator > self._working_fragment.operator:
            last_constraint = self._working_fragment.elements.pop()
            self._working_fragment = self._working_fragment \
                    .create_nested_expression()
            self._working_fragment.add_element(last_constraint)
            self._working_fragment.add_operator(operator)
        elif operator < self._working_fragment.operator:
            if self._working_fragment.parent:
                return self._working_fragment.parent.add_operator(operator)
            else:
                return Expression().add_element(self._working_fragment) \
                        .add_operator(operator)
        return self


Instruction:
Implement a Python 3 function for
adding an element of type Operator Constraint or Expression to the Expression.

Response:
def add_element(self, element):
        """Add an element of type ``Operator``, ``Constraint``, or
        ``Expression`` to the ``Expression``.

        Args:
            element: ``Constraint``, ``Expression``, or ``Operator``.

        Returns:
            Expression: ``self``

        Raises:
            FiqlObjectException: Element is not a valid type.
        """
        if isinstance(element, BaseExpression):
            element.set_parent(self._working_fragment)
            self._working_fragment.elements.append(element)
            return self
        else:
            return self.add_operator(element)


Instruction:
Create a Python 3 function for
updating the Expression by joining the specified additional Locales with an AND operator.

Response:
def op_and(self, *elements):
        """Update the ``Expression`` by joining the specified additional
        ``elements`` using an "AND" ``Operator``

        Args:
            *elements (BaseExpression): The ``Expression`` and/or
                ``Constraint`` elements which the "AND" ``Operator`` applies
                to.

        Returns:
            Expression: ``self`` or related ``Expression``.
        """
        expression = self.add_operator(Operator(';'))
        for element in elements:
            expression.add_element(element)
        return expression


Instruction:
Can you generate a brief explanation for the following Python 3 code
def op_or(self, *elements):
        expression = self.add_operator(Operator(','))
        for element in elements:
            expression.add_element(element)
        return expression

Response:
Update the expression by joining the specified additional
Locales with an OR operator.


Instruction:
Write a Python 3 function that can
decorate passed in function and log message to module logger.

Response:
def logger(function):
    """Decorate passed in function and log message to module logger."""
    @functools.wraps(function)
    def wrapper(*args, **kwargs):
        """Wrap function."""
        sep = kwargs.get('sep', ' ')
        end = kwargs.get('end', '')  # do not add newline by default
        out = sep.join([repr(x) for x in args])
        out = out + end
        _LOGGER.debug(out)
        return function(*args, **kwargs)
    return wrapper


Instruction:
Implement a Python 3 function for
parsing the received response from the socket server into a list of OrderedDicts.

Response:
def _parse_receive(incomming):
    """Parse received response.

    Parameters
    ----------
    incomming : bytes string
        Incomming bytes from socket server.

    Returns
    -------
    list of OrderedDict
        Received message as a list of OrderedDict.

    """
    debug(b'< ' + incomming)
    # remove terminating null byte
    incomming = incomming.rstrip(b'\x00')
    # split received messages
    # return as list of several messages received
    msgs = incomming.splitlines()
    return [bytes_as_dict(msg) for msg in msgs]


Instruction:
Write a Python 3 function for
formatting list of tuples to bytes

Response:
def tuples_as_bytes(cmds):
    """Format list of tuples to CAM message with format /key:val.

    Parameters
    ----------
    cmds : list of tuples
        List of commands as tuples.

    Returns
    -------
    bytes
        Sequence of /key:val.

    Example
    -------
    ::

        >>> tuples_as_bytes([('cmd', 'val'), ('cmd2', 'val2')])
        b'/cmd:val /cmd2:val2'

    """
    cmds = OrderedDict(cmds)  # override equal keys
    tmp = []
    for key, val in cmds.items():
        key = str(key)
        val = str(val)
        tmp.append('/' + key + ':' + val)
    return ' '.join(tmp).encode()


Instruction:
Can you implement a function in Python 3 that
translates a list of tuples to OrderedDict with key and val as strings.

Response:
def tuples_as_dict(_list):
    """Translate a list of tuples to OrderedDict with key and val as strings.

    Parameters
    ----------
    _list : list of tuples

    Returns
    -------
    collections.OrderedDict

    Example
    -------
    ::

        >>> tuples_as_dict([('cmd', 'val'), ('cmd2', 'val2')])
        OrderedDict([('cmd', 'val'), ('cmd2', 'val2')])

    """
    _dict = OrderedDict()
    for key, val in _list:
        key = str(key)
        val = str(val)
        _dict[key] = val
    return _dict


Instruction:
Create a Python 3 function for
parsing bytes into OrderedDict based on format / key : val.

Response:
def bytes_as_dict(msg):
    """Parse CAM message to OrderedDict based on format /key:val.

    Parameters
    ----------
    msg : bytes
        Sequence of /key:val.

    Returns
    -------
    collections.OrderedDict
        With /key:val => dict[key] = val.

    """
    # decode bytes, assume '/' in start
    cmd_strings = msg.decode()[1:].split(r' /')
    cmds = OrderedDict()
    for cmd in cmd_strings:
        unpacked = cmd.split(':')
        # handle string not well formated (ex filenames with c:\)
        if len(unpacked) > 2:
            key = unpacked[0]
            val = ':'.join(unpacked[1:])
        elif len(unpacked) < 2:
            continue
        else:
            key, val = unpacked
        cmds[key] = val
    return cmds


Instruction:
Can you generate the documentation for the following Python 3 function
def check_messages(msgs, cmd, value=None):
    for msg in msgs:
        if value and msg.get(cmd) == value:
            return msg
        if not value and msg.get(cmd):
            return msg
    return None

Response: Checks if a specific message is present in the microscope CAM interface.


Instruction:
Write a Python 3 function that can
prepare message to be sent.

Response:
def _prepare_send(self, commands):
        """Prepare message to be sent.

        Parameters
        ----------
        commands : list of tuples or bytes string
            Commands as a list of tuples or a bytes string. cam.prefix is
            allways prepended before sending.

        Returns
        -------
        string
            Message to be sent.

        """
        if isinstance(commands, bytes):
            msg = self.prefix_bytes + commands
        else:
            msg = tuples_as_bytes(self.prefix + commands)
        debug(b'> ' + msg)
        return msg


Instruction:
Given the following Python 3 function, write the documentation
def connect(self):
        self.socket = socket.socket()
        self.socket.connect((self.host, self.port))
        self.socket.settimeout(False)  # non-blocking
        sleep(self.delay)  # wait for response
        self.welcome_msg = self.socket.recv(
            self.buffer_size)

Response: Connect to LASAF through a CAM - socket.


Instruction:
Can you tell what is the following Python 3 function doing
def flush(self):
        debug('flushing incomming socket messages')
        try:
            while True:
                msg = self.socket.recv(self.buffer_size)
                debug(b'< ' + msg)
        except socket.error:
            pass

Response: Flush incomming socket messages.


Instruction:
How would you explain what the following Python 3 function does
def send(self, commands):
        self.flush()  # discard any waiting messages
        msg = self._prepare_send(commands)
        return self.socket.send(msg)

Response: Send commands to LASAF through CAM - socket.


Instruction:
Implement a function in Python 3 to
receive a message from the socket interface as list of OrderedDict.

Response:
def receive(self):
        """Receive message from socket interface as list of OrderedDict."""
        try:
            incomming = self.socket.recv(self.buffer_size)
        except socket.error:
            return []

        return _parse_receive(incomming)


Instruction:
Can you tell what is the following Python 3 function doing
def wait_for(self, cmd, value=None, timeout=60):
        wait = time() + timeout * 60
        while True:
            if time() > wait:
                return OrderedDict()
            msgs = self.receive()
            msg = check_messages(msgs, cmd, value=value)
            if msg:
                return msg
            sleep(self.delay)

Response: Wait until command is received.


Instruction:
Given the following Python 3 function, write the documentation
def enable(self, slide=0, wellx=1, welly=1, fieldx=1, fieldy=1):
        # pylint: disable=too-many-arguments
        cmd = [
            ('cmd', 'enable'),
            ('slide', str(slide)),
            ('wellx', str(wellx)),
            ('welly', str(welly)),
            ('fieldx', str(fieldx)),
            ('fieldy', str(fieldy)),
            ('value', 'true')
        ]
        self.send(cmd)
        return self.wait_for(*cmd[0])

Response: Enable a given scan field.


Instruction:
How would you explain what the following Python 3 function does
def save_template(self, filename="{ScanningTemplate}leicacam.xml"):
        cmd = [
            ('sys', '0'),
            ('cmd', 'save'),
            ('fil', str(filename))
        ]
        self.send(cmd)
        return self.wait_for(*cmd[0])

Response: Save scanning template to file.


Instruction:
Here you have a function in Python 3, explain what it does
def load_template(self, filename="{ScanningTemplate}leicacam.xml"):
        basename = os.path.basename(filename)
        if basename[-4:] == '.xml':
            basename = basename[:-4]
        if basename[:18] != '{ScanningTemplate}':
            basename = '{ScanningTemplate}' + basename
        cmd = [
            ('sys', '0'),
            ('cmd', 'load'),
            ('fil', str(basename))
        ]
        self.send(cmd)
        return self.wait_for(*cmd[1])

Response: Load scanning template from file.


Instruction:
How would you code a function in Python 3 to
get information about given keyword. Defaults to stage.

Response:
def get_information(self, about='stage'):
        """Get information about given keyword. Defaults to stage."""
        cmd = [
            ('cmd', 'getinfo'),
            ('dev', str(about))
        ]
        self.send(cmd)
        return self.wait_for(*cmd[1])