Instruction:
Given the following Python 3 function, write the documentation
def visit_module(self, node):
        self._to_consume = [NamesConsumer(node, "module")]
        self._postponed_evaluation_enabled = is_postponed_evaluation_enabled(node)

        for name, stmts in node.locals.items():
            if utils.is_builtin(name) and not utils.is_inside_except(stmts[0]):
                if self._should_ignore_redefined_builtin(stmts[0]) or name == "__doc__":
                    continue
                self.add_message("redefined-builtin", args=name, node=stmts[0])

Response:
update consumption analysis variable
        checks globals doesn t overrides builtins


Instruction:
Can you generate a brief explanation for the following Python 3 code
def leave_module(self, node):
        assert len(self._to_consume) == 1
        not_consumed = self._to_consume.pop().to_consume
        # attempt to check for __all__ if defined
        if "__all__" in node.locals:
            self._check_all(node, not_consumed)

        # check for unused globals
        self._check_globals(not_consumed)

        # don't check unused imports in __init__ files
        if not self.config.init_import and node.package:
            return

        self._check_imports(not_consumed)

Response:
leave module check globals
        check imports


Instruction:
Make a summary of the following Python 3 code
def visit_functiondef(self, node):
        self._to_consume.append(NamesConsumer(node, "function"))
        if not (
            self.linter.is_message_enabled("redefined-outer-name")
            or self.linter.is_message_enabled("redefined-builtin")
        ):
            return
        globs = node.root().globals
        for name, stmt in node.items():
            if utils.is_inside_except(stmt):
                continue
            if name in globs and not isinstance(stmt, astroid.Global):
                definition = globs[name][0]
                if (
                    isinstance(definition, astroid.ImportFrom)
                    and definition.modname == FUTURE
                ):
                    # It is a __future__ directive, not a symbol.
                    continue

                line = definition.fromlineno
                if not self._is_name_ignored(stmt, name):
                    self.add_message(
                        "redefined-outer-name", args=(name, line), node=stmt
                    )

            elif utils.is_builtin(name) and not self._should_ignore_redefined_builtin(
                stmt
            ):
                # do not print Redefining builtin for additional builtins
                self.add_message("redefined-builtin", args=name, node=stmt)

Response: update consumption analysis variable and check locals


Instruction:
Can you write a function in Python 3 where it
checks if function is not used.

Response:
def leave_functiondef(self, node):
        """leave function: check function's locals are consumed"""
        if node.type_comment_returns:
            self._store_type_annotation_node(node.type_comment_returns)
        if node.type_comment_args:
            for argument_annotation in node.type_comment_args:
                self._store_type_annotation_node(argument_annotation)

        not_consumed = self._to_consume.pop().to_consume
        if not (
            self.linter.is_message_enabled("unused-variable")
            or self.linter.is_message_enabled("possibly-unused-variable")
            or self.linter.is_message_enabled("unused-argument")
        ):
            return

        # Don't check arguments of function which are only raising an exception.
        if utils.is_error(node):
            return

        # Don't check arguments of abstract methods or within an interface.
        is_method = node.is_method()
        if is_method and node.is_abstract():
            return

        global_names = _flattened_scope_names(node.nodes_of_class(astroid.Global))
        nonlocal_names = _flattened_scope_names(node.nodes_of_class(astroid.Nonlocal))
        for name, stmts in not_consumed.items():
            self._check_is_unused(name, node, stmts[0], global_names, nonlocal_names)


Instruction:
Explain what the following Python 3 code does
def visit_global(self, node):
        frame = node.frame()
        if isinstance(frame, astroid.Module):
            self.add_message("global-at-module-level", node=node)
            return

        module = frame.root()
        default_message = True
        locals_ = node.scope().locals
        for name in node.names:
            try:
                assign_nodes = module.getattr(name)
            except astroid.NotFoundError:
                # unassigned global, skip
                assign_nodes = []

            not_defined_locally_by_import = not any(
                isinstance(local, astroid.node_classes.Import)
                for local in locals_.get(name, ())
            )
            if not assign_nodes and not_defined_locally_by_import:
                self.add_message("global-variable-not-assigned", args=name, node=node)
                default_message = False
                continue

            for anode in assign_nodes:
                if (
                    isinstance(anode, astroid.AssignName)
                    and anode.name in module.special_attributes
                ):
                    self.add_message("redefined-builtin", args=name, node=node)
                    break
                if anode.frame() is module:
                    # module level assignment
                    break
            else:
                if not_defined_locally_by_import:
                    # global undefined at the module scope
                    self.add_message("global-variable-undefined", args=name, node=node)
                    default_message = False

        if default_message:
            self.add_message("global-statement", node=node)

Response: check names imported exists in the global scope


Instruction:
Make a summary of the following Python 3 code
def _ignore_class_scope(self, node):
        # Detect if we are in a local class scope, as an assignment.
        # For example, the following is fair game.
        #
        # class A:
        #    b = 1
        #    c = lambda b=b: b * b
        #
        # class B:
        #    tp = 1
        #    def func(self, arg: tp):
        #        ...
        # class C:
        #    tp = 2
        #    def func(self, arg=tp):
        #        ...

        name = node.name
        frame = node.statement().scope()
        in_annotation_or_default = self._defined_in_function_definition(node, frame)
        if in_annotation_or_default:
            frame_locals = frame.parent.scope().locals
        else:
            frame_locals = frame.locals
        return not (
            (isinstance(frame, astroid.ClassDef) or in_annotation_or_default)
            and name in frame_locals
        )

Response: Return True if the node is in local class scope False otherwise.


Instruction:
Write a Python 3 function for
checking modules attribute accesses

Response:
def visit_import(self, node):
        """check modules attribute accesses"""
        if not self._analyse_fallback_blocks and utils.is_from_fallback_block(node):
            # No need to verify this, since ImportError is already
            # handled by the client code.
            return

        for name, _ in node.names:
            parts = name.split(".")
            try:
                module = next(_infer_name_module(node, parts[0]))
            except astroid.ResolveError:
                continue
            self._check_module_attrs(node, module, parts[1:])


Instruction:
How would you implement a function in Python 3 that
checks modules attribute accesses

Response:
def visit_importfrom(self, node):
        """check modules attribute accesses"""
        if not self._analyse_fallback_blocks and utils.is_from_fallback_block(node):
            # No need to verify this, since ImportError is already
            # handled by the client code.
            return

        name_parts = node.modname.split(".")
        try:
            module = node.do_import_module(name_parts[0])
        except astroid.AstroidBuildingException:
            return
        module = self._check_module_attrs(node, module, name_parts[1:])
        if not module:
            return
        for name, _ in node.names:
            if name == "*":
                continue
            self._check_module_attrs(node, module, name.split("."))


Instruction:
Can you create a Python 3 function that
checks unbalanced tuple unpacking for assignments and unpacking non - sequences as well as in case self / cls get assigned.

Response:
def visit_assign(self, node):
        """Check unbalanced tuple unpacking for assignments
        and unpacking non-sequences as well as in case self/cls
        get assigned.
        """
        self._check_self_cls_assign(node)
        if not isinstance(node.targets[0], (astroid.Tuple, astroid.List)):
            return

        targets = node.targets[0].itered()
        try:
            infered = utils.safe_infer(node.value)
            if infered is not None:
                self._check_unpacking(infered, node, targets)
        except astroid.InferenceError:
            return


Instruction:
Create a Python 3 function for
checking that self and cls don t get assigned

Response:
def _check_self_cls_assign(self, node):
        """Check that self/cls don't get assigned"""
        assign_names = {
            target.name
            for target in node.targets
            if isinstance(target, astroid.AssignName)
        }
        scope = node.scope()
        nonlocals_with_same_name = any(
            child
            for child in scope.body
            if isinstance(child, astroid.Nonlocal) and assign_names & set(child.names)
        )
        if nonlocals_with_same_name:
            scope = node.scope().parent.scope()

        if not (
            isinstance(scope, astroid.scoped_nodes.FunctionDef)
            and scope.is_method()
            and "builtins.staticmethod" not in scope.decoratornames()
        ):
            return
        argument_names = scope.argnames()
        if not argument_names:
            return
        self_cls_name = argument_names[0]
        target_assign_names = (
            target.name
            for target in node.targets
            if isinstance(target, astroid.node_classes.AssignName)
        )
        if self_cls_name in target_assign_names:
            self.add_message("self-cls-assignment", node=node, args=(self_cls_name))


Instruction:
Given the following Python 3 function, write the documentation
def _check_unpacking(self, infered, node, targets):
        if utils.is_inside_abstract_class(node):
            return
        if utils.is_comprehension(node):
            return
        if infered is astroid.Uninferable:
            return
        if (
            isinstance(infered.parent, astroid.Arguments)
            and isinstance(node.value, astroid.Name)
            and node.value.name == infered.parent.vararg
        ):
            # Variable-length argument, we can't determine the length.
            return
        if isinstance(infered, (astroid.Tuple, astroid.List)):
            # attempt to check unpacking is properly balanced
            values = infered.itered()
            if len(targets) != len(values):
                # Check if we have starred nodes.
                if any(isinstance(target, astroid.Starred) for target in targets):
                    return
                self.add_message(
                    "unbalanced-tuple-unpacking",
                    node=node,
                    args=(
                        _get_unpacking_extra_info(node, infered),
                        len(targets),
                        len(values),
                    ),
                )
        # attempt to check unpacking may be possible (ie RHS is iterable)
        else:
            if not utils.is_iterable(infered):
                self.add_message(
                    "unpacking-non-sequence",
                    node=node,
                    args=(_get_unpacking_extra_info(node, infered),),
                )

Response: Checks if the node is unbalanced and unpacking non sequences.


Instruction:
Make a summary of the following Python 3 code
def _check_module_attrs(self, node, module, module_names):
        assert isinstance(module, astroid.Module), module
        while module_names:
            name = module_names.pop(0)
            if name == "__dict__":
                module = None
                break
            try:
                module = next(module.getattr(name)[0].infer())
                if module is astroid.Uninferable:
                    return None
            except astroid.NotFoundError:
                if module.name in self._ignored_modules:
                    return None
                self.add_message(
                    "no-name-in-module", args=(name, module.name), node=node
                )
                return None
            except astroid.InferenceError:
                return None
        if module_names:
            # FIXME: other message if name is not the latest part of
            # module_names ?
            modname = module.name if module else "__dict__"
            self.add_message(
                "no-name-in-module", node=node, args=(".".join(module_names), modname)
            )
            return None
        if isinstance(module, astroid.Module):
            return module
        return None

Response: check that the module_names are accessible through the module


Instruction:
Can you tell what is the following Python 3 function doing
def _check_metaclasses(self, node):
        consumed = []  # [(scope_locals, consumed_key)]

        for child_node in node.get_children():
            if isinstance(child_node, astroid.ClassDef):
                consumed.extend(self._check_classdef_metaclasses(child_node, node))

        # Pop the consumed items, in order to avoid having
        # unused-import and unused-variable false positives
        for scope_locals, name in consumed:
            scope_locals.pop(name, None)

Response: Update consumption analysis for metaclasses.


Instruction:
Explain what the following Python 3 code does
def table_lines_from_stats(stats, _, columns):
    lines = []
    for m_type in columns:
        new = stats[m_type]
        new = "%.3f" % new if isinstance(new, float) else str(new)
        lines += (m_type.replace("_", " "), new, "NC", "NC")
    return lines

Response:
get values listed in columns from stats and old_stats and a
    and return a formated list of values


Instruction:
Here you have a function in Python 3, explain what it does
def ensure_scripts(linux_scripts):
    from distutils import util

    if util.get_platform()[:3] == "win":
        return linux_scripts + [script + ".bat" for script in linux_scripts]
    return linux_scripts

Response: Creates the proper script names required for each platform


Instruction:
Create a Python 3 function to
return a list of subpackages for the given directory

Response:
def get_packages(directory, prefix):
    """return a list of subpackages for the given directory"""
    result = []
    for package in os.listdir(directory):
        absfile = join(directory, package)
        if isdir(absfile):
            if exists(join(absfile, "__init__.py")):
                if prefix:
                    result.append("%s.%s" % (prefix, package))
                else:
                    result.append(package)
                result += get_packages(absfile, result[-1])
    return result


Instruction:
How would you explain what the following Python 3 function does
def run(self):
        install_lib.install_lib.run(self)
        # manually install included directories if any
        if include_dirs:
            for directory in include_dirs:
                dest = join(self.install_dir, directory)
                if sys.version_info >= (3, 0):
                    exclude = {"invalid_encoded_data*", "unknown_encoding*"}
                else:
                    exclude = set()
                shutil.rmtree(dest, ignore_errors=True)
                shutil.copytree(
                    directory, dest, ignore=shutil.ignore_patterns(*exclude)
                )

Response: run method that installs any of the include directories


Instruction:
Given the following Python 3 function, write the documentation
def stripped_lines(lines, ignore_comments, ignore_docstrings, ignore_imports):
    if ignore_imports:
        tree = astroid.parse("".join(lines))
        node_is_import_by_lineno = (
            (node.lineno, isinstance(node, (astroid.Import, astroid.ImportFrom)))
            for node in tree.body
        )
        line_begins_import = {
            lineno: all(is_import for _, is_import in node_is_import_group)
            for lineno, node_is_import_group in groupby(
                node_is_import_by_lineno, key=lambda x: x[0]
            )
        }
        current_line_is_import = False

    strippedlines = []
    docstring = None
    for lineno, line in enumerate(lines, start=1):
        line = line.strip()
        if ignore_docstrings:
            if not docstring and any(
                line.startswith(i) for i in ['"""', "'''", 'r"""', "r'''"]
            ):
                docstring = line[:3]
                line = line[3:]
            if docstring:
                if line.endswith(docstring):
                    docstring = None
                line = ""
        if ignore_imports:
            current_line_is_import = line_begins_import.get(
                lineno, current_line_is_import
            )
            if current_line_is_import:
                line = ""
        if ignore_comments:
            # XXX should use regex in checkers/format to avoid cutting
            # at a "#" in a string
            line = line.split("#", 1)[0].strip()
        strippedlines.append(line)
    return strippedlines

Response:
return lines with leading and trailing whitespace and any ignored code
            features removed


Instruction:
Create a Python 3 function to
make a layout with some stats about duplication

Response:
def report_similarities(sect, stats, old_stats):
    """make a layout with some stats about duplication"""
    lines = ["", "now", "previous", "difference"]
    lines += table_lines_from_stats(
        stats, old_stats, ("nb_duplicated_lines", "percent_duplicated_lines")
    )
    sect.append(Table(children=lines, cols=4, rheaders=1, cheaders=1))


Instruction:
Can you implement a function in Python 3 that
runs the standalone command line access point.

Response:
def Run(argv=None):
    """standalone command line access point"""
    if argv is None:
        argv = sys.argv[1:]
    from getopt import getopt

    s_opts = "hdi"
    l_opts = (
        "help",
        "duplicates=",
        "ignore-comments",
        "ignore-imports",
        "ignore-docstrings",
    )
    min_lines = 4
    ignore_comments = False
    ignore_docstrings = False
    ignore_imports = False
    opts, args = getopt(argv, s_opts, l_opts)
    for opt, val in opts:
        if opt in ("-d", "--duplicates"):
            min_lines = int(val)
        elif opt in ("-h", "--help"):
            usage()
        elif opt in ("-i", "--ignore-comments"):
            ignore_comments = True
        elif opt in ("--ignore-docstrings",):
            ignore_docstrings = True
        elif opt in ("--ignore-imports",):
            ignore_imports = True
    if not args:
        usage(1)
    sim = Similar(min_lines, ignore_comments, ignore_docstrings, ignore_imports)
    for filename in args:
        with open(filename) as stream:
            sim.append_stream(filename, stream)
    sim.run()
    sys.exit(0)


Instruction:
Can you create a Python 3 function that
appends a file to search for similarities

Response:
def append_stream(self, streamid, stream, encoding=None):
        """append a file to search for similarities"""
        if encoding is None:
            readlines = stream.readlines
        else:
            readlines = decoding_stream(stream, encoding).readlines
        try:
            self.linesets.append(
                LineSet(
                    streamid,
                    readlines(),
                    self.ignore_comments,
                    self.ignore_docstrings,
                    self.ignore_imports,
                )
            )
        except UnicodeDecodeError:
            pass


Instruction:
Write a Python 3 script to
compute similarities in appended files

Response:
def _compute_sims(self):
        """compute similarities in appended files"""
        no_duplicates = defaultdict(list)
        for num, lineset1, idx1, lineset2, idx2 in self._iter_sims():
            duplicate = no_duplicates[num]
            for couples in duplicate:
                if (lineset1, idx1) in couples or (lineset2, idx2) in couples:
                    couples.add((lineset1, idx1))
                    couples.add((lineset2, idx2))
                    break
            else:
                duplicate.append({(lineset1, idx1), (lineset2, idx2)})
        sims = []
        for num, ensembles in no_duplicates.items():
            for couples in ensembles:
                sims.append((num, couples))
        sims.sort()
        sims.reverse()
        return sims


Instruction:
Can you generate the documentation for the following Python 3 function
def _display_sims(self, sims):
        nb_lignes_dupliquees = 0
        for num, couples in sims:
            print()
            print(num, "similar lines in", len(couples), "files")
            couples = sorted(couples)
            for lineset, idx in couples:
                print("==%s:%s" % (lineset.name, idx))
            # pylint: disable=W0631
            for line in lineset._real_lines[idx : idx + num]:
                print("  ", line.rstrip())
            nb_lignes_dupliquees += num * (len(couples) - 1)
        nb_total_lignes = sum([len(lineset) for lineset in self.linesets])
        print(
            "TOTAL lines=%s duplicates=%s percent=%.2f"
            % (
                nb_total_lignes,
                nb_lignes_dupliquees,
                nb_lignes_dupliquees * 100.0 / nb_total_lignes,
            )
        )

Response: display computed similarities on stdout


Instruction:
Can you generate the documentation for the following Python 3 function
def _find_common(self, lineset1, lineset2):
        lines1 = lineset1.enumerate_stripped
        lines2 = lineset2.enumerate_stripped
        find = lineset2.find
        index1 = 0
        min_lines = self.min_lines
        while index1 < len(lineset1):
            skip = 1
            num = 0
            for index2 in find(lineset1[index1]):
                non_blank = 0
                for num, ((_, line1), (_, line2)) in enumerate(
                    zip(lines1(index1), lines2(index2))
                ):
                    if line1 != line2:
                        if non_blank > min_lines:
                            yield num, lineset1, index1, lineset2, index2
                        skip = max(skip, num)
                        break
                    if line1:
                        non_blank += 1
                else:
                    # we may have reach the end
                    num += 1
                    if non_blank > min_lines:
                        yield num, lineset1, index1, lineset2, index2
                    skip = max(skip, num)
            index1 += skip

Response: find similarities in the two given linesets


Instruction:
How would you code a function in Python 3 to
iterate on similarities among all files

Response:
def _iter_sims(self):
        """iterate on similarities among all files, by making a cartesian
        product
        """
        for idx, lineset in enumerate(self.linesets[:-1]):
            for lineset2 in self.linesets[idx + 1 :]:
                for sim in self._find_common(lineset, lineset2):
                    yield sim


Instruction:
How would you implement a function in Python 3 that
returns an iterator on stripped lines starting from a given index. start_at is the index of the first line that starts from 0.

Response:
def enumerate_stripped(self, start_at=0):
        """return an iterator on stripped lines, starting from a given index
        if specified, else 0
        """
        idx = start_at
        if start_at:
            lines = self._stripped_lines[start_at:]
        else:
            lines = self._stripped_lines
        for line in lines:
            # if line:
            yield idx, line
            idx += 1


Instruction:
Can you create a Python 3 function that
creates the index for this set

Response:
def _mk_index(self):
        """create the index for this set"""
        index = defaultdict(list)
        for line_no, line in enumerate(self._stripped_lines):
            if line:
                index[line].append(line_no)
        return index


Instruction:
Here you have a function in Python 3, explain what it does
def set_option(self, optname, value, action=None, optdict=None):
        BaseChecker.set_option(self, optname, value, action, optdict)
        if optname == "min-similarity-lines":
            self.min_lines = self.config.min_similarity_lines
        elif optname == "ignore-comments":
            self.ignore_comments = self.config.ignore_comments
        elif optname == "ignore-docstrings":
            self.ignore_docstrings = self.config.ignore_docstrings
        elif optname == "ignore-imports":
            self.ignore_imports = self.config.ignore_imports

Response: set an option in the configuration


Instruction:
How would you explain what the following Python 3 function does
def process_module(self, node):
        with node.stream() as stream:
            self.append_stream(self.linter.current_name, stream, node.file_encoding)

Response: process a module by appending the stream to the current name


Instruction:
Can you create a Python 3 function that
computes and display similarities on closing ( i. e. end of parsing

Response:
def close(self):
        """compute and display similarities on closing (i.e. end of parsing)"""
        total = sum(len(lineset) for lineset in self.linesets)
        duplicated = 0
        stats = self.stats
        for num, couples in self._compute_sims():
            msg = []
            for lineset, idx in couples:
                msg.append("==%s:%s" % (lineset.name, idx))
            msg.sort()
            # pylint: disable=W0631
            for line in lineset._real_lines[idx : idx + num]:
                msg.append(line.rstrip())
            self.add_message("R0801", args=(len(couples), "\n".join(msg)))
            duplicated += num * (len(couples) - 1)
        stats["nb_duplicated_lines"] = duplicated
        stats["percent_duplicated_lines"] = total and duplicated * 100.0 / total


Instruction:
How would you implement a function in Python 3 that
checks if a definition signature is equivalent to a call.

Response:
def _definition_equivalent_to_call(definition, call):
    """Check if a definition signature is equivalent to a call."""
    if definition.kwargs:
        same_kw_variadics = definition.kwargs in call.starred_kws
    else:
        same_kw_variadics = not call.starred_kws
    if definition.varargs:
        same_args_variadics = definition.varargs in call.starred_args
    else:
        same_args_variadics = not call.starred_args
    same_kwonlyargs = all(kw in call.kws for kw in definition.kwonlyargs)
    same_args = definition.args == call.args

    no_additional_kwarg_arguments = True
    if call.kws:
        for keyword in call.kws:
            is_arg = keyword in call.args
            is_kwonly = keyword in definition.kwonlyargs
            if not is_arg and not is_kwonly:
                # Maybe this argument goes into **kwargs,
                # or it is an extraneous argument.
                # In any case, the signature is different than
                # the call site, which stops our search.
                no_additional_kwarg_arguments = False
                break

    return all(
        (
            same_args,
            same_kwonlyargs,
            same_args_variadics,
            same_kw_variadics,
            no_additional_kwarg_arguments,
        )
    )


Instruction:
Can you create a Python 3 function that
checks if the attributes of node_a and node_b are equal.

Response:
def _check_arg_equality(node_a, node_b, attr_name):
    """
    Check equality of nodes based on the comparison of their attributes named attr_name.

    Args:
        node_a (astroid.node): first node to compare.
        node_b (astroid.node): second node to compare.
        attr_name (str): name of the nodes attribute to use for comparison.

    Returns:
        bool: True if node_a.attr_name == node_b.attr_name, False otherwise.
    """
    return getattr(node_a, attr_name) == getattr(node_b, attr_name)


Instruction:
Given the following Python 3 function, write the documentation
def _has_different_parameters_default_value(original, overridden):
    if original.args is None or overridden.args is None:
        return False

    all_args = chain(original.args, original.kwonlyargs)
    original_param_names = [param.name for param in all_args]
    default_missing = object()
    for param_name in original_param_names:
        try:
            original_default = original.default_value(param_name)
        except astroid.exceptions.NoDefault:
            original_default = default_missing
        try:
            overridden_default = overridden.default_value(param_name)
        except astroid.exceptions.NoDefault:
            overridden_default = default_missing

        default_list = [
            arg == default_missing for arg in (original_default, overridden_default)
        ]
        if any(default_list) and not all(default_list):
            # Only one arg has no default value
            return True

        astroid_type_compared_attr = {
            astroid.Const: "value",
            astroid.ClassDef: "name",
            astroid.Tuple: "elts",
            astroid.List: "elts",
        }
        handled_types = tuple(
            astroid_type for astroid_type in astroid_type_compared_attr
        )
        original_type = _get_node_type(original_default, handled_types)
        if original_type:
            #  We handle only astroid types that are inside the dict astroid_type_compared_attr
            if not isinstance(overridden_default, original_type):
                #  Two args with same name but different types
                return True
            if not _check_arg_equality(
                original_default,
                overridden_default,
                astroid_type_compared_attr[original_type],
            ):
                # Two args with same type but different values
                return True
    return False

Response: Check if one of the original and overridden methods arguments have different default values


Instruction:
Create a Python 3 function for
determining if two methods have different parameters.

Response:
def _different_parameters(original, overridden, dummy_parameter_regex):
    """Determine if the two methods have different parameters

    They are considered to have different parameters if:

       * they have different positional parameters, including different names

       * one of the methods is having variadics, while the other is not

       * they have different keyword only parameters.

    """
    original_parameters = _positional_parameters(original)
    overridden_parameters = _positional_parameters(overridden)

    different_positional = _has_different_parameters(
        original_parameters, overridden_parameters, dummy_parameter_regex
    )
    different_kwonly = _has_different_parameters(
        original.args.kwonlyargs, overridden.args.kwonlyargs, dummy_parameter_regex
    )
    if original.name in PYMETHODS:
        # Ignore the difference for special methods. If the parameter
        # numbers are different, then that is going to be caught by
        # unexpected-special-method-signature.
        # If the names are different, it doesn't matter, since they can't
        # be used as keyword arguments anyway.
        different_positional = different_kwonly = False

    # Both or none should have extra variadics, otherwise the method
    # loses or gains capabilities that are not reflected into the parent method,
    # leading to potential inconsistencies in the code.
    different_kwarg = (
        sum(1 for param in (original.args.kwarg, overridden.args.kwarg) if not param)
        == 1
    )
    different_vararg = (
        sum(1 for param in (original.args.vararg, overridden.args.vararg) if not param)
        == 1
    )

    return any(
        (different_positional, different_kwarg, different_vararg, different_kwonly)
    )


Instruction:
Can you generate the documentation for the following Python 3 function
def _called_in_methods(func, klass, methods):
    if not isinstance(func, astroid.FunctionDef):
        return False
    for method in methods:
        try:
            infered = klass.getattr(method)
        except astroid.NotFoundError:
            continue
        for infer_method in infered:
            for call in infer_method.nodes_of_class(astroid.Call):
                try:
                    bound = next(call.func.infer())
                except (astroid.InferenceError, StopIteration):
                    continue
                if not isinstance(bound, astroid.BoundMethod):
                    continue
                func_obj = bound._proxied
                if isinstance(func_obj, astroid.UnboundMethod):
                    func_obj = func_obj._proxied
                if func_obj.name == func.name:
                    return True
    return False

Response: Check if the given function was called in any of the given methods. Returns True if so False otherwise.


Instruction:
Write a Python 3 function for
checking if the given attribute name is a property in the given klass.

Response:
def _is_attribute_property(name, klass):
    """ Check if the given attribute *name* is a property
    in the given *klass*.

    It will look for `property` calls or for functions
    with the given name, decorated by `property` or `property`
    subclasses.
    Returns ``True`` if the name is a property in the given klass,
    ``False`` otherwise.
    """

    try:
        attributes = klass.getattr(name)
    except astroid.NotFoundError:
        return False
    property_name = "{}.property".format(BUILTINS)
    for attr in attributes:
        if attr is astroid.Uninferable:
            continue
        try:
            infered = next(attr.infer())
        except astroid.InferenceError:
            continue
        if isinstance(infered, astroid.FunctionDef) and decorated_with_property(
            infered
        ):
            return True
        if infered.pytype() == property_name:
            return True
    return False


Instruction:
Make a summary of the following Python 3 code
def _safe_infer_call_result(node, caller, context=None):
    try:
        inferit = node.infer_call_result(caller, context=context)
        value = next(inferit)
    except astroid.InferenceError:
        return None  # inference failed
    except StopIteration:
        return None  # no values infered
    try:
        next(inferit)
        return None  # there is ambiguity on the inferred node
    except astroid.InferenceError:
        return None  # there is some kind of ambiguity
    except StopIteration:
        return value

Response: Safely infer the return value of a function call.


Instruction:
Here you have a function in Python 3, explain what it does
def _ancestors_to_call(klass_node, method="__init__"):
    to_call = {}
    for base_node in klass_node.ancestors(recurs=False):
        try:
            to_call[base_node] = next(base_node.igetattr(method))
        except astroid.InferenceError:
            continue
    return to_call

Response:
return a dictionary where keys are the list of base classes providing
    the queried method and so that should be called from the method node node


Instruction:
How would you code a function in Python 3 to
require method to auto register this checker

Response:
def register(linter):
    """required method to auto register this checker """
    linter.register_checker(ClassChecker(linter))
    linter.register_checker(SpecialMethodsChecker(linter))


Instruction:
Here you have a function in Python 3, explain what it does
def set_accessed(self, node):

        frame = node_frame_class(node)
        if frame is None:
            # The node does not live in a class.
            return
        self._scopes[frame][node.attrname].append(node)

Response: Set the given node as accessed.


Instruction:
Given the following Python 3 function, write the documentation
def visit_classdef(self, node):
        self._check_bases_classes(node)
        # if not an exception or a metaclass
        if node.type == "class" and has_known_bases(node):
            try:
                node.local_attr("__init__")
            except astroid.NotFoundError:
                self.add_message("no-init", args=node, node=node)
        self._check_slots(node)
        self._check_proper_bases(node)
        self._check_consistent_mro(node)

Response: check if class is not an exception or a metaclass


Instruction:
Can you generate the documentation for the following Python 3 function
def _check_consistent_mro(self, node):
        try:
            node.mro()
        except InconsistentMroError:
            self.add_message("inconsistent-mro", args=node.name, node=node)
        except DuplicateBasesError:
            self.add_message("duplicate-bases", args=node.name, node=node)
        except NotImplementedError:
            # Old style class, there's no mro so don't do anything.
            pass

Response: Detect that a class has a consistent mro or duplicate bases.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _check_proper_bases(self, node):
        for base in node.bases:
            ancestor = safe_infer(base)
            if ancestor in (astroid.Uninferable, None):
                continue
            if isinstance(ancestor, astroid.Instance) and ancestor.is_subtype_of(
                "%s.type" % (BUILTINS,)
            ):
                continue

            if not isinstance(ancestor, astroid.ClassDef) or _is_invalid_base_class(
                ancestor
            ):
                self.add_message("inherit-non-class", args=base.as_string(), node=node)

            if ancestor.name == object.__name__:
                self.add_message(
                    "useless-object-inheritance", args=node.name, node=node
                )

Response: Detects that a class inherits something which is not an instance or a type.


Instruction:
Here you have a function in Python 3, explain what it does
def leave_classdef(self, cnode):
        # check access to existent members on non metaclass classes
        if self._ignore_mixin and cnode.name[-5:].lower() == "mixin":
            # We are in a mixin class. No need to try to figure out if
            # something is missing, since it is most likely that it will
            # miss.
            return

        accessed = self._accessed.accessed(cnode)
        if cnode.type != "metaclass":
            self._check_accessed_members(cnode, accessed)
        # checks attributes are defined in an allowed method such as __init__
        if not self.linter.is_message_enabled("attribute-defined-outside-init"):
            return
        defining_methods = self.config.defining_attr_methods
        current_module = cnode.root()
        for attr, nodes in cnode.instance_attrs.items():
            # skip nodes which are not in the current module and it may screw up
            # the output, while it's not worth it
            nodes = [
                n
                for n in nodes
                if not isinstance(n.statement(), (astroid.Delete, astroid.AugAssign))
                and n.root() is current_module
            ]
            if not nodes:
                continue  # error detected by typechecking
            # check if any method attr is defined in is a defining method
            if any(node.frame().name in defining_methods for node in nodes):
                continue

            # check attribute is defined in a parent's __init__
            for parent in cnode.instance_attr_ancestors(attr):
                attr_defined = False
                # check if any parent method attr is defined in is a defining method
                for node in parent.instance_attrs[attr]:
                    if node.frame().name in defining_methods:
                        attr_defined = True
                if attr_defined:
                    # we're done :)
                    break
            else:
                # check attribute is defined as a class attribute
                try:
                    cnode.local_attr(attr)
                except astroid.NotFoundError:
                    for node in nodes:
                        if node.frame().name not in defining_methods:
                            # If the attribute was set by a call in any
                            # of the defining methods, then don't emit
                            # the warning.
                            if _called_in_methods(
                                node.frame(), cnode, defining_methods
                            ):
                                continue
                            self.add_message(
                                "attribute-defined-outside-init", args=attr, node=node
                            )

Response: close a class node check that instance attributes are defined in __init__ and check that all members of the class are in the same module as the class.


Instruction:
Make a summary of the following Python 3 code
def visit_functiondef(self, node):
        # ignore actual functions
        if not node.is_method():
            return

        self._check_useless_super_delegation(node)

        klass = node.parent.frame()
        self._meth_could_be_func = True
        # check first argument is self if this is actually a method
        self._check_first_arg_for_type(node, klass.type == "metaclass")
        if node.name == "__init__":
            self._check_init(node)
            return
        # check signature if the method overloads inherited method
        for overridden in klass.local_attr_ancestors(node.name):
            # get astroid for the searched method
            try:
                meth_node = overridden[node.name]
            except KeyError:
                # we have found the method but it's not in the local
                # dictionary.
                # This may happen with astroid build from living objects
                continue
            if not isinstance(meth_node, astroid.FunctionDef):
                continue
            self._check_signature(node, meth_node, "overridden", klass)
            break
        if node.decorators:
            for decorator in node.decorators.nodes:
                if isinstance(decorator, astroid.Attribute) and decorator.attrname in (
                    "getter",
                    "setter",
                    "deleter",
                ):
                    # attribute affectation will call this method, not hiding it
                    return
                if isinstance(decorator, astroid.Name):
                    if decorator.name == "property":
                        # attribute affectation will either call a setter or raise
                        # an attribute error, anyway not hiding the function
                        return

                # Infer the decorator and see if it returns something useful
                inferred = safe_infer(decorator)
                if not inferred:
                    return
                if isinstance(inferred, astroid.FunctionDef):
                    # Okay, it's a decorator, let's see what it can infer.
                    try:
                        inferred = next(inferred.infer_call_result(inferred))
                    except astroid.InferenceError:
                        return
                try:
                    if (
                        isinstance(inferred, (astroid.Instance, astroid.ClassDef))
                        and inferred.getattr("__get__")
                        and inferred.getattr("__set__")
                    ):
                        return
                except astroid.AttributeInferenceError:
                    pass

        # check if the method is hidden by an attribute
        try:
            overridden = klass.instance_attr(node.name)[0]  # XXX
            overridden_frame = overridden.frame()
            if (
                isinstance(overridden_frame, astroid.FunctionDef)
                and overridden_frame.type == "method"
            ):
                overridden_frame = overridden_frame.parent.frame()
            if isinstance(overridden_frame, astroid.ClassDef) and klass.is_subtype_of(
                overridden_frame.qname()
            ):
                args = (overridden.root().name, overridden.fromlineno)
                self.add_message("method-hidden", args=args, node=node)
        except astroid.NotFoundError:
            pass

Response: Check if the node is a method or method.


Instruction:
How would you implement a function in Python 3 that
checks if the given function node is an useless method override

Response:
def _check_useless_super_delegation(self, function):
        """Check if the given function node is an useless method override

        We consider it *useless* if it uses the super() builtin, but having
        nothing additional whatsoever than not implementing the method at all.
        If the method uses super() to delegate an operation to the rest of the MRO,
        and if the method called is the same as the current one, the arguments
        passed to super() are the same as the parameters that were passed to
        this method, then the method could be removed altogether, by letting
        other implementation to take precedence.
        """

        if (
            not function.is_method()
            # With decorators is a change of use
            or function.decorators
        ):
            return

        body = function.body
        if len(body) != 1:
            # Multiple statements, which means this overridden method
            # could do multiple things we are not aware of.
            return

        statement = body[0]
        if not isinstance(statement, (astroid.Expr, astroid.Return)):
            # Doing something else than what we are interested into.
            return

        call = statement.value
        if (
            not isinstance(call, astroid.Call)
            # Not a super() attribute access.
            or not isinstance(call.func, astroid.Attribute)
        ):
            return

        # Should be a super call.
        try:
            super_call = next(call.func.expr.infer())
        except astroid.InferenceError:
            return
        else:
            if not isinstance(super_call, objects.Super):
                return

        # The name should be the same.
        if call.func.attrname != function.name:
            return

        # Should be a super call with the MRO pointer being the
        # current class and the type being the current instance.
        current_scope = function.parent.scope()
        if (
            super_call.mro_pointer != current_scope
            or not isinstance(super_call.type, astroid.Instance)
            or super_call.type.name != current_scope.name
        ):
            return

        #  Check values of default args
        klass = function.parent.frame()
        meth_node = None
        for overridden in klass.local_attr_ancestors(function.name):
            # get astroid for the searched method
            try:
                meth_node = overridden[function.name]
            except KeyError:
                # we have found the method but it's not in the local
                # dictionary.
                # This may happen with astroid build from living objects
                continue
            if (
                not isinstance(meth_node, astroid.FunctionDef)
                # If the method have an ancestor which is not a
                # function then it is legitimate to redefine it
                or _has_different_parameters_default_value(
                    meth_node.args, function.args
                )
            ):
                return
            break

        # Detect if the parameters are the same as the call's arguments.
        params = _signature_from_arguments(function.args)
        args = _signature_from_call(call)

        if meth_node is not None:

            def form_annotations(annotations):
                return [
                    annotation.as_string() for annotation in filter(None, annotations)
                ]

            called_annotations = form_annotations(function.args.annotations)
            overridden_annotations = form_annotations(meth_node.args.annotations)
            if called_annotations and overridden_annotations:
                if called_annotations != overridden_annotations:
                    return

        if _definition_equivalent_to_call(params, args):
            self.add_message(
                "useless-super-delegation", node=function, args=(function.name,)
            )


Instruction:
Can you generate a brief explanation for the following Python 3 code
def leave_functiondef(self, node):
        if node.is_method():
            if node.args.args is not None:
                self._first_attrs.pop()
            if not self.linter.is_message_enabled("no-self-use"):
                return
            class_node = node.parent.frame()
            if (
                self._meth_could_be_func
                and node.type == "method"
                and node.name not in PYMETHODS
                and not (
                    node.is_abstract()
                    or overrides_a_method(class_node, node.name)
                    or decorated_with_property(node)
                    or _has_bare_super_call(node)
                )
            ):
                self.add_message("no-self-use", node=node)

Response: check if this function couldn t be a function


Instruction:
Create a Python 3 function to
check if the getattr is an access to a class member and register it if so

Response:
def visit_attribute(self, node):
        """check if the getattr is an access to a class member
        if so, register it. Also check for access to protected
        class member from outside its class (but ignore __special__
        methods)
        """
        # Check self
        if self._uses_mandatory_method_param(node):
            self._accessed.set_accessed(node)
            return
        if not self.linter.is_message_enabled("protected-access"):
            return

        self._check_protected_attribute_access(node)


Instruction:
Can you implement a function in Python 3 that
checks that the given AssignAttr node is defined in the class slots.

Response:
def _check_in_slots(self, node):
        """ Check that the given AssignAttr node
        is defined in the class slots.
        """
        inferred = safe_infer(node.expr)
        if not isinstance(inferred, astroid.Instance):
            return

        klass = inferred._proxied
        if not has_known_bases(klass):
            return
        if "__slots__" not in klass.locals or not klass.newstyle:
            return

        slots = klass.slots()
        if slots is None:
            return
        # If any ancestor doesn't use slots, the slots
        # defined for this class are superfluous.
        if any(
            "__slots__" not in ancestor.locals and ancestor.name != "object"
            for ancestor in klass.ancestors()
        ):
            return

        if not any(slot.value == node.attrname for slot in slots):
            # If we have a '__dict__' in slots, then
            # assigning any name is valid.
            if not any(slot.value == "__dict__" for slot in slots):
                if _is_attribute_property(node.attrname, klass):
                    # Properties circumvent the slots mechanism,
                    # so we should not emit a warning for them.
                    return
                if node.attrname in klass.locals and _has_data_descriptor(
                    klass, node.attrname
                ):
                    # Descriptors circumvent the slots mechanism as well.
                    return
                if node.attrname == "__class__" and _has_same_layout_slots(
                    slots, node.parent.value
                ):
                    return
                self.add_message("assigning-non-slot", args=(node.attrname,), node=node)


Instruction:
Can you generate the documentation for the following Python 3 function
def _check_classmethod_declaration(self, node):
        if not isinstance(node.value, astroid.Call):
            return

        # check the function called is "classmethod" or "staticmethod"
        func = node.value.func
        if not isinstance(func, astroid.Name) or func.name not in (
            "classmethod",
            "staticmethod",
        ):
            return

        msg = (
            "no-classmethod-decorator"
            if func.name == "classmethod"
            else "no-staticmethod-decorator"
        )
        # assignment must be at a class scope
        parent_class = node.scope()
        if not isinstance(parent_class, astroid.ClassDef):
            return

        # Check if the arg passed to classmethod is a class member
        classmeth_arg = node.value.args[0]
        if not isinstance(classmeth_arg, astroid.Name):
            return

        method_name = classmeth_arg.name
        if any(method_name == member.name for member in parent_class.mymethods()):
            self.add_message(msg, node=node.targets[0])

Response: Checks for uses of classmethod or staticmethod.


Instruction:
Make a summary of the following Python 3 code
def _check_protected_attribute_access(self, node):
        attrname = node.attrname

        if (
            is_attr_protected(attrname)
            and attrname not in self.config.exclude_protected
        ):

            klass = node_frame_class(node)

            # XXX infer to be more safe and less dirty ??
            # in classes, check we are not getting a parent method
            # through the class object or through super
            callee = node.expr.as_string()

            # We are not in a class, no remaining valid case
            if klass is None:
                self.add_message("protected-access", node=node, args=attrname)
                return

            # If the expression begins with a call to super, that's ok.
            if (
                isinstance(node.expr, astroid.Call)
                and isinstance(node.expr.func, astroid.Name)
                and node.expr.func.name == "super"
            ):
                return

            # If the expression begins with a call to type(self), that's ok.
            if self._is_type_self_call(node.expr):
                return

            # We are in a class, one remaining valid cases, Klass._attr inside
            # Klass
            if not (callee == klass.name or callee in klass.basenames):
                # Detect property assignments in the body of the class.
                # This is acceptable:
                #
                # class A:
                #     b = property(lambda: self._b)

                stmt = node.parent.statement()
                if (
                    isinstance(stmt, astroid.Assign)
                    and len(stmt.targets) == 1
                    and isinstance(stmt.targets[0], astroid.AssignName)
                ):
                    name = stmt.targets[0].name
                    if _is_attribute_property(name, klass):
                        return

                self.add_message("protected-access", node=node, args=attrname)

Response: Checks if the node is a protected attribute access.


Instruction:
How would you explain what the following Python 3 function does
def visit_name(self, node):
        if self._first_attrs and (
            node.name == self._first_attrs[-1] or not self._first_attrs[-1]
        ):
            self._meth_could_be_func = False

Response: check if the name handle an access to a class member


Instruction:
Implement a function in Python 3 to
check that all members of a node are defined

Response:
def _check_accessed_members(self, node, accessed):
        """check that accessed members are defined"""
        # XXX refactor, probably much simpler now that E0201 is in type checker
        excs = ("AttributeError", "Exception", "BaseException")
        for attr, nodes in accessed.items():
            try:
                # is it a class attribute ?
                node.local_attr(attr)
                # yes, stop here
                continue
            except astroid.NotFoundError:
                pass
            # is it an instance attribute of a parent class ?
            try:
                next(node.instance_attr_ancestors(attr))
                # yes, stop here
                continue
            except StopIteration:
                pass
            # is it an instance attribute ?
            try:
                defstmts = node.instance_attr(attr)
            except astroid.NotFoundError:
                pass
            else:
                # filter out augment assignment nodes
                defstmts = [stmt for stmt in defstmts if stmt not in nodes]
                if not defstmts:
                    # only augment assignment for this node, no-member should be
                    # triggered by the typecheck checker
                    continue
                # filter defstmts to only pick the first one when there are
                # several assignments in the same scope
                scope = defstmts[0].scope()
                defstmts = [
                    stmt
                    for i, stmt in enumerate(defstmts)
                    if i == 0 or stmt.scope() is not scope
                ]
                # if there are still more than one, don't attempt to be smarter
                # than we can be
                if len(defstmts) == 1:
                    defstmt = defstmts[0]
                    # check that if the node is accessed in the same method as
                    # it's defined, it's accessed after the initial assignment
                    frame = defstmt.frame()
                    lno = defstmt.fromlineno
                    for _node in nodes:
                        if (
                            _node.frame() is frame
                            and _node.fromlineno < lno
                            and not astroid.are_exclusive(
                                _node.statement(), defstmt, excs
                            )
                        ):
                            self.add_message(
                                "access-member-before-definition",
                                node=_node,
                                args=(attr, lno),
                            )


Instruction:
How would you explain what the following Python 3 function does
def _check_first_arg_for_type(self, node, metaclass=0):
        # don't care about functions with unknown argument (builtins)
        if node.args.args is None:
            return
        first_arg = node.args.args and node.argnames()[0]
        self._first_attrs.append(first_arg)
        first = self._first_attrs[-1]
        # static method
        if node.type == "staticmethod":
            if (
                first_arg == "self"
                or first_arg in self.config.valid_classmethod_first_arg
                or first_arg in self.config.valid_metaclass_classmethod_first_arg
            ):
                self.add_message("bad-staticmethod-argument", args=first, node=node)
                return
            self._first_attrs[-1] = None
        # class / regular method with no args
        elif not node.args.args:
            self.add_message("no-method-argument", node=node)
        # metaclass
        elif metaclass:
            # metaclass __new__ or classmethod
            if node.type == "classmethod":
                self._check_first_arg_config(
                    first,
                    self.config.valid_metaclass_classmethod_first_arg,
                    node,
                    "bad-mcs-classmethod-argument",
                    node.name,
                )
            # metaclass regular method
            else:
                self._check_first_arg_config(
                    first,
                    self.config.valid_classmethod_first_arg,
                    node,
                    "bad-mcs-method-argument",
                    node.name,
                )
        # regular class
        else:
            # class method
            if node.type == "classmethod" or node.name == "__class_getitem__":
                self._check_first_arg_config(
                    first,
                    self.config.valid_classmethod_first_arg,
                    node,
                    "bad-classmethod-argument",
                    node.name,
                )
            # regular method without self as argument
            elif first != "self":
                self.add_message("no-self-argument", node=node)

Response: check the first argument for the type of class or regular method


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _check_bases_classes(self, node):

        def is_abstract(method):
            return method.is_abstract(pass_is_abstract=False)

        # check if this class abstract
        if class_is_abstract(node):
            return

        methods = sorted(
            unimplemented_abstract_methods(node, is_abstract).items(),
            key=lambda item: item[0],
        )
        for name, method in methods:
            owner = method.parent.frame()
            if owner is node:
                continue
            # owner is not this class, it must be a parent class
            # check that the ancestor's method is not abstract
            if name in node.locals:
                # it is redefined as an attribute or with a descriptor
                continue
            self.add_message("abstract-method", node=node, args=(name, owner.name))

Response:
check that the given class node implements abstract methods from
        base classes


Instruction:
Write a Python 3 script for
checking that the __init__ method call super or ancestors - super - init - not - called

Response:
def _check_init(self, node):
        """check that the __init__ method call super or ancestors'__init__
        method
        """
        if not self.linter.is_message_enabled(
            "super-init-not-called"
        ) and not self.linter.is_message_enabled("non-parent-init-called"):
            return
        klass_node = node.parent.frame()
        to_call = _ancestors_to_call(klass_node)
        not_called_yet = dict(to_call)
        for stmt in node.nodes_of_class(astroid.Call):
            expr = stmt.func
            if not isinstance(expr, astroid.Attribute) or expr.attrname != "__init__":
                continue
            # skip the test if using super
            if (
                isinstance(expr.expr, astroid.Call)
                and isinstance(expr.expr.func, astroid.Name)
                and expr.expr.func.name == "super"
            ):
                return
            try:
                for klass in expr.expr.infer():
                    if klass is astroid.Uninferable:
                        continue
                    # The infered klass can be super(), which was
                    # assigned to a variable and the `__init__`
                    # was called later.
                    #
                    # base = super()
                    # base.__init__(...)

                    if (
                        isinstance(klass, astroid.Instance)
                        and isinstance(klass._proxied, astroid.ClassDef)
                        and is_builtin_object(klass._proxied)
                        and klass._proxied.name == "super"
                    ):
                        return
                    if isinstance(klass, objects.Super):
                        return
                    try:
                        del not_called_yet[klass]
                    except KeyError:
                        if klass not in to_call:
                            self.add_message(
                                "non-parent-init-called", node=expr, args=klass.name
                            )
            except astroid.InferenceError:
                continue
        for klass, method in not_called_yet.items():
            cls = node_frame_class(method)
            if klass.name == "object" or (cls and cls.name == "object"):
                continue
            self.add_message("super-init-not-called", args=klass.name, node=node)


Instruction:
Write a Python 3 script to
check that the signature of the two given methods match the signature of the class

Response:
def _check_signature(self, method1, refmethod, class_type, cls):
        """check that the signature of the two given methods match
        """
        if not (
            isinstance(method1, astroid.FunctionDef)
            and isinstance(refmethod, astroid.FunctionDef)
        ):
            self.add_message(
                "method-check-failed", args=(method1, refmethod), node=method1
            )
            return

        instance = cls.instantiate_class()
        method1 = function_to_method(method1, instance)
        refmethod = function_to_method(refmethod, instance)

        # Don't care about functions with unknown argument (builtins).
        if method1.args.args is None or refmethod.args.args is None:
            return

        # Ignore private to class methods.
        if is_attr_private(method1.name):
            return
        # Ignore setters, they have an implicit extra argument,
        # which shouldn't be taken in consideration.
        if method1.decorators:
            for decorator in method1.decorators.nodes:
                if (
                    isinstance(decorator, astroid.Attribute)
                    and decorator.attrname == "setter"
                ):
                    return

        if _different_parameters(
            refmethod, method1, dummy_parameter_regex=self._dummy_rgx
        ):
            self.add_message(
                "arguments-differ", args=(class_type, method1.name), node=method1
            )
        elif len(method1.args.defaults) < len(refmethod.args.defaults):
            self.add_message(
                "signature-differs", args=(class_type, method1.name), node=method1
            )


Instruction:
Explain what the following Python 3 code does
def _is_mandatory_method_param(self, node):
        return (
            self._first_attrs
            and isinstance(node, astroid.Name)
            and node.name == self._first_attrs[-1]
        )

Response: Check if node is a mandatory method parameter.


Instruction:
Write a Python 3 script for
returning an iterator which yields tuples of nodes inferred by the given statement.

Response:
def _annotated_unpack_infer(stmt, context=None):
    """
    Recursively generate nodes inferred by the given statement.
    If the inferred value is a list or a tuple, recurse on the elements.
    Returns an iterator which yields tuples in the format
    ('original node', 'infered node').
    """
    if isinstance(stmt, (astroid.List, astroid.Tuple)):
        for elt in stmt.elts:
            inferred = utils.safe_infer(elt)
            if inferred and inferred is not astroid.Uninferable:
                yield elt, inferred
        return
    for infered in stmt.infer(context):
        if infered is astroid.Uninferable:
            continue
        yield stmt, infered


Instruction:
Given the following Python 3 function, write the documentation
def _is_raising(body: typing.List) -> bool:
    for node in body:
        if isinstance(node, astroid.Raise):
            return True
    return False

Response: Return true if the given statement node raise an exception


Instruction:
Can you implement a function in Python 3 that
verifies that the exception context is properly set.

Response:
def _check_bad_exception_context(self, node):
        """Verify that the exception context is properly set.

        An exception context can be only `None` or an exception.
        """
        cause = utils.safe_infer(node.cause)
        if cause in (astroid.Uninferable, None):
            return

        if isinstance(cause, astroid.Const):
            if cause.value is not None:
                self.add_message("bad-exception-context", node=node)
        elif not isinstance(cause, astroid.ClassDef) and not utils.inherit_from_std_ex(
            cause
        ):
            self.add_message("bad-exception-context", node=node)


Instruction:
Can you write a function in Python 3 where it
checks for empty except clause and raise exceptions.

Response:
def visit_tryexcept(self, node):
        """check for empty except"""
        self._check_try_except_raise(node)
        exceptions_classes = []
        nb_handlers = len(node.handlers)
        for index, handler in enumerate(node.handlers):
            if handler.type is None:
                if not _is_raising(handler.body):
                    self.add_message("bare-except", node=handler)

                # check if an "except:" is followed by some other
                # except
                if index < (nb_handlers - 1):
                    msg = "empty except clause should always appear last"
                    self.add_message("bad-except-order", node=node, args=msg)

            elif isinstance(handler.type, astroid.BoolOp):
                self.add_message(
                    "binary-op-exception", node=handler, args=handler.type.op
                )
            else:
                try:
                    excs = list(_annotated_unpack_infer(handler.type))
                except astroid.InferenceError:
                    continue

                for part, exc in excs:
                    if exc is astroid.Uninferable:
                        continue
                    if isinstance(exc, astroid.Instance) and utils.inherit_from_std_ex(
                        exc
                    ):
                        # pylint: disable=protected-access
                        exc = exc._proxied

                    self._check_catching_non_exception(handler, exc, part)

                    if not isinstance(exc, astroid.ClassDef):
                        continue

                    exc_ancestors = [
                        anc
                        for anc in exc.ancestors()
                        if isinstance(anc, astroid.ClassDef)
                    ]

                    for previous_exc in exceptions_classes:
                        if previous_exc in exc_ancestors:
                            msg = "%s is an ancestor class of %s" % (
                                previous_exc.name,
                                exc.name,
                            )
                            self.add_message(
                                "bad-except-order", node=handler.type, args=msg
                            )
                    if (
                        exc.name in self.config.overgeneral_exceptions
                        and exc.root().name == utils.EXCEPTIONS_MODULE
                        and not _is_raising(handler.body)
                    ):
                        self.add_message(
                            "broad-except", args=exc.name, node=handler.type
                        )

                    if exc in exceptions_classes:
                        self.add_message(
                            "duplicate-except", args=exc.name, node=handler.type
                        )

                exceptions_classes += [exc for _, exc in excs]


Instruction:
Can you generate a brief explanation for the following Python 3 code
def visit_functiondef(self, node):
        # ignore actual functions or method within a new style class
        if not node.is_method():
            return
        klass = node.parent.frame()
        for stmt in node.nodes_of_class(astroid.Call):
            if node_frame_class(stmt) != node_frame_class(node):
                # Don't look down in other scopes.
                continue

            expr = stmt.func
            if not isinstance(expr, astroid.Attribute):
                continue

            call = expr.expr
            # skip the test if using super
            if not (
                isinstance(call, astroid.Call)
                and isinstance(call.func, astroid.Name)
                and call.func.name == "super"
            ):
                continue

            if not klass.newstyle and has_known_bases(klass):
                # super should not be used on an old style class
                continue
            else:
                # super first arg should be the class
                if not call.args:
                    if sys.version_info[0] == 3:
                        # unless Python 3
                        continue
                    else:
                        self.add_message("missing-super-argument", node=call)
                        continue

                # calling super(type(self), self) can lead to recursion loop
                # in derived classes
                arg0 = call.args[0]
                if (
                    isinstance(arg0, astroid.Call)
                    and isinstance(arg0.func, astroid.Name)
                    and arg0.func.name == "type"
                ):
                    self.add_message("bad-super-call", node=call, args=("type",))
                    continue

                # calling super(self.__class__, self) can lead to recursion loop
                # in derived classes
                if (
                    len(call.args) >= 2
                    and isinstance(call.args[1], astroid.Name)
                    and call.args[1].name == "self"
                    and isinstance(arg0, astroid.Attribute)
                    and arg0.attrname == "__class__"
                ):
                    self.add_message(
                        "bad-super-call", node=call, args=("self.__class__",)
                    )
                    continue

                try:
                    supcls = call.args and next(call.args[0].infer(), None)
                except astroid.InferenceError:
                    continue

                if klass is not supcls:
                    name = None
                    # if supcls is not Uninferable, then supcls was infered
                    # and use its name. Otherwise, try to look
                    # for call.args[0].name
                    if supcls:
                        name = supcls.name
                    elif call.args and hasattr(call.args[0], "name"):
                        name = call.args[0].name
                    if name:
                        self.add_message("bad-super-call", node=call, args=(name,))

Response: check use of super


Instruction:
Can you tell what is the following Python 3 function doing
def display_reports(self, layout):
        self.section = 0
        if hasattr(layout, "report_id"):
            layout.children[0].children[0].data += " (%s)" % layout.report_id
        self._display(layout)

Response: display results encapsulated in the layout tree


Instruction:
Can you create a Python 3 function that
checks if a class node is a typing. NamedTuple class

Response:
def _is_typing_namedtuple(node: astroid.ClassDef) -> bool:
    """Check if a class node is a typing.NamedTuple class"""
    for base in node.ancestors():
        if base.qname() == TYPING_NAMEDTUPLE:
            return True
    return False


Instruction:
Here you have a function in Python 3, explain what it does
def _is_enum_class(node: astroid.ClassDef) -> bool:
    for base in node.bases:
        try:
            inferred_bases = base.inferred()
        except astroid.InferenceError:
            continue

        for ancestor in inferred_bases:
            if not isinstance(ancestor, astroid.ClassDef):
                continue

            if ancestor.name == "Enum" and ancestor.root().name == "enum":
                return True

    return False

Response: Checks if a class definition defines an Enum class.


Instruction:
How would you explain what the following Python 3 function does
def _is_dataclass(node: astroid.ClassDef) -> bool:
    if not node.decorators:
        return False

    root_locals = node.root().locals
    for decorator in node.decorators.nodes:
        if isinstance(decorator, astroid.Call):
            decorator = decorator.func
        if not isinstance(decorator, (astroid.Name, astroid.Attribute)):
            continue
        if isinstance(decorator, astroid.Name):
            name = decorator.name
        else:
            name = decorator.attrname
        if name == DATACLASS_DECORATOR and DATACLASS_DECORATOR in root_locals:
            return True
    return False

Response: Check if a given class node is a dataclass class.


Instruction:
Write a Python 3 function that can
count the number of boolean expressions in BoolOp bool_op.

Response:
def _count_boolean_expressions(bool_op):
    """Counts the number of boolean expressions in BoolOp `bool_op` (recursive)

    example: a and (b or c or (d and e)) ==> 5 boolean expressions
    """
    nb_bool_expr = 0
    for bool_expr in bool_op.get_children():
        if isinstance(bool_expr, BoolOp):
            nb_bool_expr += _count_boolean_expressions(bool_expr)
        else:
            nb_bool_expr += 1
    return nb_bool_expr


Instruction:
Here you have a function in Python 3, explain what it does
def visit_classdef(self, node):
        nb_parents = len(list(node.ancestors()))
        if nb_parents > self.config.max_parents:
            self.add_message(
                "too-many-ancestors",
                node=node,
                args=(nb_parents, self.config.max_parents),
            )

        if len(node.instance_attrs) > self.config.max_attributes:
            self.add_message(
                "too-many-instance-attributes",
                node=node,
                args=(len(node.instance_attrs), self.config.max_attributes),
            )

Response: check size of inheritance hierarchy and number of instance attributes


Instruction:
Create a Python 3 function for
checking if the current class has at least one public method.

Response:
def leave_classdef(self, node):
        """check number of public methods"""
        my_methods = sum(
            1 for method in node.mymethods() if not method.name.startswith("_")
        )

        # Does the class contain less than n public methods ?
        # This checks only the methods defined in the current class,
        # since the user might not have control over the classes
        # from the ancestors. It avoids some false positives
        # for classes such as unittest.TestCase, which provides
        # a lot of assert methods. It doesn't make sense to warn
        # when the user subclasses TestCase to add his own tests.
        if my_methods > self.config.max_public_methods:
            self.add_message(
                "too-many-public-methods",
                node=node,
                args=(my_methods, self.config.max_public_methods),
            )

        # Stop here for exception, metaclass, interface classes and other
        # classes for which we don't need to count the methods.
        if (
            node.type != "class"
            or _is_enum_class(node)
            or _is_dataclass(node)
            or _is_typing_namedtuple(node)
        ):
            return

        # Does the class contain more than n public methods ?
        # This checks all the methods defined by ancestors and
        # by the current class.
        all_methods = _count_methods_in_class(node)
        if all_methods < self.config.min_public_methods:
            self.add_message(
                "too-few-public-methods",
                node=node,
                args=(all_methods, self.config.min_public_methods),
            )


Instruction:
Can you implement a function in Python 3 that
checks function name docstring arguments redefinition variable names max locals

Response:
def visit_functiondef(self, node):
        """check function name, docstring, arguments, redefinition,
        variable names, max locals
        """
        # init branch and returns counters
        self._returns.append(0)
        # check number of arguments
        args = node.args.args
        ignored_argument_names = self._ignored_argument_names
        if args is not None:
            ignored_args_num = 0
            if ignored_argument_names:
                ignored_args_num = sum(
                    1 for arg in args if ignored_argument_names.match(arg.name)
                )

            argnum = len(args) - ignored_args_num
            if argnum > self.config.max_args:
                self.add_message(
                    "too-many-arguments",
                    node=node,
                    args=(len(args), self.config.max_args),
                )
        else:
            ignored_args_num = 0
        # check number of local variables
        locnum = len(node.locals) - ignored_args_num
        if locnum > self.config.max_locals:
            self.add_message(
                "too-many-locals", node=node, args=(locnum, self.config.max_locals)
            )
        # init new statements counter
        self._stmts.append(1)


Instruction:
Explain what the following Python 3 code does
def leave_functiondef(self, node):
        returns = self._returns.pop()
        if returns > self.config.max_returns:
            self.add_message(
                "too-many-return-statements",
                node=node,
                args=(returns, self.config.max_returns),
            )
        branches = self._branches[node]
        if branches > self.config.max_branches:
            self.add_message(
                "too-many-branches",
                node=node,
                args=(branches, self.config.max_branches),
            )
        # check number of statements
        stmts = self._stmts.pop()
        if stmts > self.config.max_statements:
            self.add_message(
                "too-many-statements",
                node=node,
                args=(stmts, self.config.max_statements),
            )

Response: leaves the functiondef node


Instruction:
Implement a function in Python 3 to
increment the branches counter node.orelse is the exception node.

Response:
def visit_tryexcept(self, node):
        """increments the branches counter"""
        branches = len(node.handlers)
        if node.orelse:
            branches += 1
        self._inc_branch(node, branches)
        self._inc_all_stmts(branches)


Instruction:
How would you explain what the following Python 3 function does
def visit_if(self, node):
        self._check_boolean_expressions(node)
        branches = 1
        # don't double count If nodes coming from some 'elif'
        if node.orelse and (len(node.orelse) > 1 or not isinstance(node.orelse[0], If)):
            branches += 1
        self._inc_branch(node, branches)
        self._inc_all_stmts(branches)

Response: visit an If node and update the branches counter and checks boolean expressions and the all statements that are in the branch.


Instruction:
Can you generate the documentation for the following Python 3 function
def _check_boolean_expressions(self, node):
        condition = node.test
        if not isinstance(condition, BoolOp):
            return
        nb_bool_expr = _count_boolean_expressions(condition)
        if nb_bool_expr > self.config.max_bool_expr:
            self.add_message(
                "too-many-boolean-expressions",
                node=condition,
                args=(nb_bool_expr, self.config.max_bool_expr),
            )

Response:
Go through the if node and counts its boolean expressions
            if the condition is a BoolOp node


Instruction:
Can you generate the documentation for the following Python 3 function
def visit_while(self, node):
        branches = 1
        if node.orelse:
            branches += 1
        self._inc_branch(node, branches)

Response: increments the branches counter


Instruction:
Given the following Python 3 function, write the documentation
def _check_docstring(self, node):
        docstring = node.doc
        if not docstring:
            return

        start_line = node.lineno + 1

        # Go through lines of docstring
        for idx, line in enumerate(docstring.splitlines()):
            self._check_spelling("wrong-spelling-in-docstring", line, start_line + idx)

Response: check the node has any spelling errors


Instruction:
Here you have a function in Python 3, explain what it does
def format(self, template):
        # For some reason, _asdict on derived namedtuples does not work with
        # Python 3.4. Needs some investigation.
        return template.format(**dict(zip(self._fields, self)))

Response: Format the message according to the given template.


Instruction:
Given the following Python 3 function, write the documentation
def _is_len_call(node):
    return (
        isinstance(node, astroid.Call)
        and isinstance(node.func, astroid.Name)
        and node.func.name == "len"
    )

Response: Checks if node is len ( SOFTING


Instruction:
Create a Python 3 function for
checking if the given token is a trailing comma which trails an expression

Response:
def _is_trailing_comma(tokens, index):
    """Check if the given token is a trailing comma

    :param tokens: Sequence of modules tokens
    :type tokens: list[tokenize.TokenInfo]
    :param int index: Index of token under check in tokens
    :returns: True if the token is a comma which trails an expression
    :rtype: bool
    """
    token = tokens[index]
    if token.exact_type != tokenize.COMMA:
        return False
    # Must have remaining tokens on the same line such as NEWLINE
    left_tokens = itertools.islice(tokens, index + 1, None)
    same_line_remaining_tokens = list(
        itertools.takewhile(
            lambda other_token, _token=token: other_token.start[0] == _token.start[0],
            left_tokens,
        )
    )
    # Note: If the newline is tokenize.NEWLINE and not tokenize.NL
    # then the newline denotes the end of expression
    is_last_element = all(
        other_token.type in (tokenize.NEWLINE, tokenize.COMMENT)
        for other_token in same_line_remaining_tokens
    )
    if not same_line_remaining_tokens or not is_last_element:
        return False

    def get_curline_index_start():
        """Get the index denoting the start of the current line"""
        for subindex, token in enumerate(reversed(tokens[:index])):
            # See Lib/tokenize.py and Lib/token.py in cpython for more info
            if token.type in (tokenize.NEWLINE, tokenize.NL):
                return index - subindex
        return 0

    curline_start = get_curline_index_start()
    expected_tokens = {"return", "yield"}
    for prevtoken in tokens[curline_start:index]:
        if "=" in prevtoken.string or prevtoken.string in expected_tokens:
            return True
    return False


Instruction:
Can you generate a brief explanation for the following Python 3 code
def register(linter):
    linter.register_checker(RefactoringChecker(linter))
    linter.register_checker(NotChecker(linter))
    linter.register_checker(RecommandationChecker(linter))
    linter.register_checker(LenChecker(linter))

Response: Required method to auto register this checker.


Instruction:
Write a Python 3 script to
check if the given node is an actual elif node.

Response:
def _is_actual_elif(self, node):
        """Check if the given node is an actual elif

        This is a problem we're having with the builtin ast module,
        which splits `elif` branches into a separate if statement.
        Unfortunately we need to know the exact type in certain
        cases.
        """
        if isinstance(node.parent, astroid.If):
            orelse = node.parent.orelse
            # current if node must directly follow an "else"
            if orelse and orelse == [node]:
                if (node.lineno, node.col_offset) in self._elifs:
                    return True
        return False


Instruction:
Can you generate the documentation for the following Python 3 function
def _check_simplifiable_if(self, node):

        if self._is_actual_elif(node):
            # Not interested in if statements with multiple branches.
            return
        if len(node.orelse) != 1 or len(node.body) != 1:
            return

        # Check if both branches can be reduced.
        first_branch = node.body[0]
        else_branch = node.orelse[0]
        if isinstance(first_branch, astroid.Return):
            if not isinstance(else_branch, astroid.Return):
                return
            first_branch_is_bool = self._is_bool_const(first_branch)
            else_branch_is_bool = self._is_bool_const(else_branch)
            reduced_to = "'return bool(test)'"
        elif isinstance(first_branch, astroid.Assign):
            if not isinstance(else_branch, astroid.Assign):
                return

            # Check if we assign to the same value
            first_branch_targets = [
                target.name
                for target in first_branch.targets
                if isinstance(target, astroid.AssignName)
            ]
            else_branch_targets = [
                target.name
                for target in else_branch.targets
                if isinstance(target, astroid.AssignName)
            ]
            if not first_branch_targets or not else_branch_targets:
                return
            if sorted(first_branch_targets) != sorted(else_branch_targets):
                return

            first_branch_is_bool = self._is_bool_const(first_branch)
            else_branch_is_bool = self._is_bool_const(else_branch)
            reduced_to = "'var = bool(test)'"
        else:
            return

        if not first_branch_is_bool or not else_branch_is_bool:
            return
        if not first_branch.value.value:
            # This is a case that can't be easily simplified and
            # if it can be simplified, it will usually result in a
            # code that's harder to understand and comprehend.
            # Let's take for instance `arg and arg <= 3`. This could theoretically be
            # reduced to `not arg or arg > 3`, but the net result is that now the
            # condition is harder to understand, because it requires understanding of
            # an extra clause:
            #   * first, there is the negation of truthness with `not arg`
            #   * the second clause is `arg > 3`, which occurs when arg has a
            #     a truth value, but it implies that `arg > 3` is equivalent
            #     with `arg and arg > 3`, which means that the user must
            #     think about this assumption when evaluating `arg > 3`.
            #     The original form is easier to grasp.
            return

        self.add_message("simplifiable-if-statement", node=node, args=(reduced_to,))

Response: Check if the given if node can be simplified.


Instruction:
How would you explain what the following Python 3 function does
def _check_stop_iteration_inside_generator(self, node):
        frame = node.frame()
        if not isinstance(frame, astroid.FunctionDef) or not frame.is_generator():
            return
        if utils.node_ignores_exception(node, StopIteration):
            return
        if not node.exc:
            return
        exc = utils.safe_infer(node.exc)
        if exc is None or exc is astroid.Uninferable:
            return
        if self._check_exception_inherit_from_stopiteration(exc):
            self.add_message("stop-iteration-return", node=node)

Response: Check if an exception of type StopIteration is raised inside a generator


Instruction:
Can you generate the documentation for the following Python 3 function
def _check_exception_inherit_from_stopiteration(exc):
        stopiteration_qname = "{}.StopIteration".format(utils.EXCEPTIONS_MODULE)
        return any(_class.qname() == stopiteration_qname for _class in exc.mro())

Response: Return True if the exception node in argument inherit from StopIteration


Instruction:
Explain what the following Python 3 code does
def _check_raising_stopiteration_in_generator_next_call(self, node):

        def _looks_like_infinite_iterator(param):
            inferred = utils.safe_infer(param)
            if inferred:
                return inferred.qname() in KNOWN_INFINITE_ITERATORS
            return False

        if isinstance(node.func, astroid.Attribute):
            # A next() method, which is now what we want.
            return

        inferred = utils.safe_infer(node.func)
        if getattr(inferred, "name", "") == "next":
            frame = node.frame()
            # The next builtin can only have up to two
            # positional arguments and no keyword arguments
            has_sentinel_value = len(node.args) > 1
            if (
                isinstance(frame, astroid.FunctionDef)
                and frame.is_generator()
                and not has_sentinel_value
                and not utils.node_ignores_exception(node, StopIteration)
                and not _looks_like_infinite_iterator(node.args[0])
            ):
                self.add_message("stop-iteration-return", node=node)

Response:
Check if a StopIteration exception is raised by the next call to next function
           .


Instruction:
Can you generate the documentation for the following Python 3 function
def _check_nested_blocks(self, node):
        # only check block levels inside functions or methods
        if not isinstance(node.scope(), astroid.FunctionDef):
            return
        # messages are triggered on leaving the nested block. Here we save the
        # stack in case the current node isn't nested in the previous one
        nested_blocks = self._nested_blocks[:]
        if node.parent == node.scope():
            self._nested_blocks = [node]
        else:
            # go through ancestors from the most nested to the less
            for ancestor_node in reversed(self._nested_blocks):
                if ancestor_node == node.parent:
                    break
                self._nested_blocks.pop()
            # if the node is an elif, this should not be another nesting level
            if isinstance(node, astroid.If) and self._is_actual_elif(node):
                if self._nested_blocks:
                    self._nested_blocks.pop()
            self._nested_blocks.append(node)

        # send message only once per group of nested blocks
        if len(nested_blocks) > len(self._nested_blocks):
            self._emit_nested_blocks_message_if_needed(nested_blocks)

Response: Update and check the number of nested blocks in the current node


Instruction:
Make a summary of the following Python 3 code
def _duplicated_isinstance_types(node):
        duplicated_objects = set()
        all_types = collections.defaultdict(set)

        for call in node.values:
            if not isinstance(call, astroid.Call) or len(call.args) != 2:
                continue

            inferred = utils.safe_infer(call.func)
            if not inferred or not utils.is_builtin_object(inferred):
                continue

            if inferred.name != "isinstance":
                continue

            isinstance_object = call.args[0].as_string()
            isinstance_types = call.args[1]

            if isinstance_object in all_types:
                duplicated_objects.add(isinstance_object)

            if isinstance(isinstance_types, astroid.Tuple):
                elems = [
                    class_type.as_string() for class_type in isinstance_types.itered()
                ]
            else:
                elems = [isinstance_types.as_string()]
            all_types[isinstance_object].update(elems)

        # Remove all keys which not duplicated
        return {
            key: value for key, value in all_types.items() if key in duplicated_objects
        }

Response: Get the duplicated types from the underlying isinstance calls.


Instruction:
Create a Python 3 function for
checking if isinstance calls which can be merged together.

Response:
def _check_consider_merging_isinstance(self, node):
        """Check isinstance calls which can be merged together."""
        if node.op != "or":
            return

        first_args = self._duplicated_isinstance_types(node)
        for duplicated_name, class_names in first_args.items():
            names = sorted(name for name in class_names)
            self.add_message(
                "consider-merging-isinstance",
                node=node,
                args=(duplicated_name, ", ".join(names)),
            )