The following issues were found

Lib/distutils/command/build_scripts.py
16 issues
Attribute 'scripts' defined outside __init__
Error

Line: 42 Column: 9

                                                 ('build_scripts', 'build_dir'),
                                   ('force', 'force'),
                                   ('executable', 'executable'))
        self.scripts = self.distribution.scripts

    def get_source_files(self):
        return self.scripts

    def run(self):

            

Reported by Pylint.

Unused variable 'lines'
Error

Line: 82 Column: 27

                                  raise
                f = None
            else:
                encoding, lines = tokenize.detect_encoding(f.readline)
                f.seek(0)
                first_line = f.readline()
                if not first_line:
                    self.warn("%s is an empty file (skipping)" % script)
                    continue

            

Reported by Pylint.

Consider explicitly re-raising using the 'from' keyword
Error

Line: 116 Column: 25

                                  try:
                        shebang.decode('utf-8')
                    except UnicodeDecodeError:
                        raise ValueError(
                            "The shebang ({!r}) is not decodable "
                            "from utf-8".format(shebang))
                    # If the script is encoded to a custom encoding (use a
                    # #coding:xxx cookie), the shebang has to be decodable from
                    # the script encoding too.

            

Reported by Pylint.

Consider explicitly re-raising using the 'from' keyword
Error

Line: 125 Column: 25

                                  try:
                        shebang.decode(encoding)
                    except UnicodeDecodeError:
                        raise ValueError(
                            "The shebang ({!r}) is not decodable "
                            "from the script encoding ({})"
                            .format(shebang, encoding))
                    with open(outfile, "wb") as outf:
                        outf.write(shebang)

            

Reported by Pylint.

XXX should we modify self.outfiles?
Error

Line: 151 Column: 3

                                      log.info("changing mode of %s from %o to %o",
                                 file, oldmode, newmode)
                        os.chmod(file, newmode)
        # XXX should we modify self.outfiles?
        return outfiles, updated_files

class build_scripts_2to3(build_scripts, Mixin2to3):

    def copy_scripts(self):

            

Reported by Pylint.

Multiple imports on one line (os, re)
Error

Line: 5 Column: 1

              
Implements the Distutils 'build_scripts' command."""

import os, re
from stat import ST_MODE
from distutils import sysconfig
from distutils.core import Command
from distutils.dep_util import newer
from distutils.util import convert_path, Mixin2to3

            

Reported by Pylint.

Class name "build_scripts" doesn't conform to PascalCase naming style
Error

Line: 17 Column: 1

              # check if Python is called on the first line with this expression
first_line_re = re.compile(b'^#!.*python[0-9.]*([ \t].*)?$')

class build_scripts(Command):

    description = "\"build\" scripts (copy and fixup #! line)"

    user_options = [
        ('build-dir=', 'd', "directory to \"build\" (copy) to"),

            

Reported by Pylint.

Missing class docstring
Error

Line: 17 Column: 1

              # check if Python is called on the first line with this expression
first_line_re = re.compile(b'^#!.*python[0-9.]*([ \t].*)?$')

class build_scripts(Command):

    description = "\"build\" scripts (copy and fixup #! line)"

    user_options = [
        ('build-dir=', 'd', "directory to \"build\" (copy) to"),

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 44 Column: 5

                                                 ('executable', 'executable'))
        self.scripts = self.distribution.scripts

    def get_source_files(self):
        return self.scripts

    def run(self):
        if not self.scripts:
            return

            

Reported by Pylint.

Too many local variables (18/15)
Error

Line: 53 Column: 5

                      self.copy_scripts()


    def copy_scripts(self):
        r"""Copy each script listed in 'self.scripts'; if it's marked as a
        Python script in the Unix way (first line matches 'first_line_re',
        ie. starts with "\#!" and contains "python"), then adjust the first
        line to refer to the current Python interpreter as we copy.
        """

            

Reported by Pylint.

Lib/lib2to3/main.py
16 issues
Attempted relative import beyond top-level package
Error

Line: 14 Column: 1

              import shutil
import optparse

from . import refactor


def diff_texts(a, b, filename):
    """Return a unified diff of two strings."""
    a = a.splitlines()

            

Reported by Pylint.

Uses of a deprecated module 'optparse'
Error

Line: 12 Column: 1

              import difflib
import logging
import shutil
import optparse

from . import refactor


def diff_texts(a, b, filename):

            

Reported by Pylint.

Argument name "b" doesn't conform to snake_case naming style
Error

Line: 17 Column: 1

              from . import refactor


def diff_texts(a, b, filename):
    """Return a unified diff of two strings."""
    a = a.splitlines()
    b = b.splitlines()
    return difflib.unified_diff(a, b, filename, filename,
                                "(original)", "(refactored)",

            

Reported by Pylint.

Argument name "a" doesn't conform to snake_case naming style
Error

Line: 17 Column: 1

              from . import refactor


def diff_texts(a, b, filename):
    """Return a unified diff of two strings."""
    a = a.splitlines()
    b = b.splitlines()
    return difflib.unified_diff(a, b, filename, filename,
                                "(original)", "(refactored)",

            

Reported by Pylint.

Too many arguments (9/5)
Error

Line: 36 Column: 5

                  where you do not want to replace the input files.
    """

    def __init__(self, fixers, options, explicit, nobackups, show_diffs,
                 input_base_dir='', output_dir='', append_suffix=''):
        """
        Args:
            fixers: A list of fixers to import.
            options: A dict with RefactoringTool configuration.

            

Reported by Pylint.

Consider using Python 3 style super() without arguments
Error

Line: 63 Column: 9

                      self._input_base_dir = input_base_dir
        self._output_dir = output_dir
        self._append_suffix = append_suffix
        super(StdoutRefactoringTool, self).__init__(fixers, options, explicit)

    def log_error(self, msg, *args, **kwargs):
        self.errors.append((msg, args, kwargs))
        self.logger.error(msg, *args, **kwargs)


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 65 Column: 5

                      self._append_suffix = append_suffix
        super(StdoutRefactoringTool, self).__init__(fixers, options, explicit)

    def log_error(self, msg, *args, **kwargs):
        self.errors.append((msg, args, kwargs))
        self.logger.error(msg, *args, **kwargs)

    def write_file(self, new_text, filename, old_text, encoding):
        orig_filename = filename

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 69 Column: 5

                      self.errors.append((msg, args, kwargs))
        self.logger.error(msg, *args, **kwargs)

    def write_file(self, new_text, filename, old_text, encoding):
        orig_filename = filename
        if self._output_dir:
            if filename.startswith(self._input_base_dir):
                filename = os.path.join(self._output_dir,
                                        filename[len(self._input_base_dir):])

            

Reported by Pylint.

Consider using Python 3 style super() without arguments
Error

Line: 100 Column: 17

                          except OSError:
                self.log_message("Can't rename %s to %s", filename, backup)
        # Actually write the new file
        write = super(StdoutRefactoringTool, self).write_file
        write(new_text, filename, old_text, encoding)
        if not self.nobackups:
            shutil.copymode(backup, filename)
        if orig_filename != filename:
            # Preserve the file mode in the new output directory.

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 108 Column: 5

                          # Preserve the file mode in the new output directory.
            shutil.copymode(orig_filename, filename)

    def print_output(self, old, new, filename, equal):
        if equal:
            self.log_message("No changes to %s", filename)
        else:
            self.log_message("Refactored %s", filename)
            if self.show_diffs:

            

Reported by Pylint.

Lib/idlelib/idle_test/test_undo.py
16 issues
Unused variable 'i'
Error

Line: 129 Column: 13

                      text = self.text
        # when number of undo operations exceeds max_undo
        self.delegator.max_undo = max_undo = 10
        for i in range(max_undo + 10):
            text.insert('insert', 'foo')
            self.assertLessEqual(len(self.delegator.undolist), max_undo)


if __name__ == '__main__':

            

Reported by Pylint.

standard import "import unittest" should be placed before "from idlelib.undo import UndoDelegator"
Error

Line: 5 Column: 1

              # Only test UndoDelegator so far.

from idlelib.undo import UndoDelegator
import unittest
from test.support import requires
requires('gui')

from unittest.mock import Mock
from tkinter import Text, Tk

            

Reported by Pylint.

standard import "from test.support import requires" should be placed before "from idlelib.undo import UndoDelegator"
Error

Line: 6 Column: 1

              
from idlelib.undo import UndoDelegator
import unittest
from test.support import requires
requires('gui')

from unittest.mock import Mock
from tkinter import Text, Tk
from idlelib.percolator import Percolator

            

Reported by Pylint.

standard import "from unittest.mock import Mock" should be placed before "from idlelib.undo import UndoDelegator"
Error

Line: 9 Column: 1

              from test.support import requires
requires('gui')

from unittest.mock import Mock
from tkinter import Text, Tk
from idlelib.percolator import Percolator


class UndoDelegatorTest(unittest.TestCase):

            

Reported by Pylint.

Import "from unittest.mock import Mock" should be placed at the top of the module
Error

Line: 9 Column: 1

              from test.support import requires
requires('gui')

from unittest.mock import Mock
from tkinter import Text, Tk
from idlelib.percolator import Percolator


class UndoDelegatorTest(unittest.TestCase):

            

Reported by Pylint.

Import "from tkinter import Text, Tk" should be placed at the top of the module
Error

Line: 10 Column: 1

              requires('gui')

from unittest.mock import Mock
from tkinter import Text, Tk
from idlelib.percolator import Percolator


class UndoDelegatorTest(unittest.TestCase):


            

Reported by Pylint.

standard import "from tkinter import Text, Tk" should be placed before "from idlelib.undo import UndoDelegator"
Error

Line: 10 Column: 1

              requires('gui')

from unittest.mock import Mock
from tkinter import Text, Tk
from idlelib.percolator import Percolator


class UndoDelegatorTest(unittest.TestCase):


            

Reported by Pylint.

Import "from idlelib.percolator import Percolator" should be placed at the top of the module
Error

Line: 11 Column: 1

              
from unittest.mock import Mock
from tkinter import Text, Tk
from idlelib.percolator import Percolator


class UndoDelegatorTest(unittest.TestCase):

    @classmethod

            

Reported by Pylint.

Missing class docstring
Error

Line: 14 Column: 1

              from idlelib.percolator import Percolator


class UndoDelegatorTest(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.root = Tk()
        cls.text = Text(cls.root)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 39 Column: 5

                      self.text.delete('1.0', 'end')
        self.delegator.resetcache()

    def test_undo_event(self):
        text = self.text

        text.insert('insert', 'foobar')
        text.insert('insert', 'h')
        text.event_generate('<<undo>>')

            

Reported by Pylint.

Lib/lib2to3/pgen2/literals.py
16 issues
Redefining built-in 'all'
Error

Line: 20 Column: 5

                                "\\": "\\"}

def escape(m):
    all, tail = m.group(0, 1)
    assert all.startswith("\\")
    esc = simple_escapes.get(tail)
    if esc is not None:
        return esc
    if tail.startswith("x"):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 19 Column: 1

                                '"': '"',
                  "\\": "\\"}

def escape(m):
    all, tail = m.group(0, 1)
    assert all.startswith("\\")
    esc = simple_escapes.get(tail)
    if esc is not None:
        return esc

            

Reported by Pylint.

Argument name "m" doesn't conform to snake_case naming style
Error

Line: 19 Column: 1

                                '"': '"',
                  "\\": "\\"}

def escape(m):
    all, tail = m.group(0, 1)
    assert all.startswith("\\")
    esc = simple_escapes.get(tail)
    if esc is not None:
        return esc

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 21
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

              
def escape(m):
    all, tail = m.group(0, 1)
    assert all.startswith("\\")
    esc = simple_escapes.get(tail)
    if esc is not None:
        return esc
    if tail.startswith("x"):
        hexes = tail[1:]

            

Reported by Bandit.

Function name "evalString" doesn't conform to snake_case naming style
Error

Line: 40 Column: 1

                          raise ValueError("invalid octal string escape ('\\%s')" % tail) from None
    return chr(i)

def evalString(s):
    assert s.startswith("'") or s.startswith('"'), repr(s[:1])
    q = s[0]
    if s[:3] == q*3:
        q = q*3
    assert s.endswith(q), repr(s[-len(q):])

            

Reported by Pylint.

Argument name "s" doesn't conform to snake_case naming style
Error

Line: 40 Column: 1

                          raise ValueError("invalid octal string escape ('\\%s')" % tail) from None
    return chr(i)

def evalString(s):
    assert s.startswith("'") or s.startswith('"'), repr(s[:1])
    q = s[0]
    if s[:3] == q*3:
        q = q*3
    assert s.endswith(q), repr(s[-len(q):])

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 40 Column: 1

                          raise ValueError("invalid octal string escape ('\\%s')" % tail) from None
    return chr(i)

def evalString(s):
    assert s.startswith("'") or s.startswith('"'), repr(s[:1])
    q = s[0]
    if s[:3] == q*3:
        q = q*3
    assert s.endswith(q), repr(s[-len(q):])

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 41
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                  return chr(i)

def evalString(s):
    assert s.startswith("'") or s.startswith('"'), repr(s[:1])
    q = s[0]
    if s[:3] == q*3:
        q = q*3
    assert s.endswith(q), repr(s[-len(q):])
    assert len(s) >= 2*len(q)

            

Reported by Bandit.

Variable name "q" doesn't conform to snake_case naming style
Error

Line: 42 Column: 5

              
def evalString(s):
    assert s.startswith("'") or s.startswith('"'), repr(s[:1])
    q = s[0]
    if s[:3] == q*3:
        q = q*3
    assert s.endswith(q), repr(s[-len(q):])
    assert len(s) >= 2*len(q)
    s = s[len(q):-len(q)]

            

Reported by Pylint.

Variable name "q" doesn't conform to snake_case naming style
Error

Line: 44 Column: 9

                  assert s.startswith("'") or s.startswith('"'), repr(s[:1])
    q = s[0]
    if s[:3] == q*3:
        q = q*3
    assert s.endswith(q), repr(s[-len(q):])
    assert len(s) >= 2*len(q)
    s = s[len(q):-len(q)]
    return re.sub(r"\\(\'|\"|\\|[abfnrtv]|x.{0,2}|[0-7]{1,3})", escape, s)


            

Reported by Pylint.

Lib/distutils/tests/test_build_scripts.py
16 issues
Redefining built-in 'dir'
Error

Line: 54 Column: 36

                          )
        return build_scripts(dist)

    def write_sample_scripts(self, dir):
        expected = []
        expected.append("script1.py")
        self.write_script(dir, "script1.py",
                          ("#! /usr/bin/env python2.3\n"
                           "# bogus script w/ Python sh-bang\n"

            

Reported by Pylint.

Redefining built-in 'dir'
Error

Line: 73 Column: 28

                                         "exit 0\n"))
        return expected

    def write_script(self, dir, name, text):
        f = open(os.path.join(dir, name), "w")
        try:
            f.write(text)
        finally:
            f.close()

            

Reported by Pylint.

Access to a protected member _config_vars of a client class
Error

Line: 97 Column: 9

                      # --with-suffix=3`, python is compiled okay but the build scripts
        # failed when writing the name of the executable
        old = sysconfig.get_config_vars().get('VERSION')
        sysconfig._config_vars['VERSION'] = 4
        try:
            cmd.run()
        finally:
            if old is not None:
                sysconfig._config_vars['VERSION'] = old

            

Reported by Pylint.

Access to a protected member _config_vars of a client class
Error

Line: 102 Column: 17

                          cmd.run()
        finally:
            if old is not None:
                sysconfig._config_vars['VERSION'] = old

        built = os.listdir(target)
        for name in expected:
            self.assertIn(name, built)


            

Reported by Pylint.

Missing class docstring
Error

Line: 14 Column: 1

              from test.support import run_unittest


class BuildScriptsTestCase(support.TempdirManager,
                           support.LoggingSilencer,
                           unittest.TestCase):

    def test_default_settings(self):
        cmd = self.get_build_scripts_cmd("/foo/bar", [])

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 18 Column: 5

                                         support.LoggingSilencer,
                           unittest.TestCase):

    def test_default_settings(self):
        cmd = self.get_build_scripts_cmd("/foo/bar", [])
        self.assertFalse(cmd.force)
        self.assertIsNone(cmd.build_dir)

        cmd.finalize_options()

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 28 Column: 5

                      self.assertTrue(cmd.force)
        self.assertEqual(cmd.build_dir, "/foo/bar")

    def test_build(self):
        source = self.mkdtemp()
        target = self.mkdtemp()
        expected = self.write_sample_scripts(source)

        cmd = self.get_build_scripts_cmd(target,

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 43 Column: 5

                      for name in expected:
            self.assertIn(name, built)

    def get_build_scripts_cmd(self, target, scripts):
        import sys
        dist = Distribution()
        dist.scripts = scripts
        dist.command_obj["build"] = support.DummyCommand(
            build_scripts=target,

            

Reported by Pylint.

Method could be a function
Error

Line: 43 Column: 5

                      for name in expected:
            self.assertIn(name, built)

    def get_build_scripts_cmd(self, target, scripts):
        import sys
        dist = Distribution()
        dist.scripts = scripts
        dist.command_obj["build"] = support.DummyCommand(
            build_scripts=target,

            

Reported by Pylint.

Import outside toplevel (sys)
Error

Line: 44 Column: 9

                          self.assertIn(name, built)

    def get_build_scripts_cmd(self, target, scripts):
        import sys
        dist = Distribution()
        dist.scripts = scripts
        dist.command_obj["build"] = support.DummyCommand(
            build_scripts=target,
            force=1,

            

Reported by Pylint.

Tools/peg_generator/pegen/testutil.py
16 issues
Use of exec
Error

Line: 35 Column: 5

              
    # Load the generated parser class.
    ns: Dict[str, Any] = {}
    exec(out.getvalue(), ns)
    return ns["GeneratedParser"]


def run_parser(file: IO[bytes], parser_class: Type[Parser], *, verbose: bool = False) -> Any:
    # Run a parser on a file (stream).

            

Reported by Pylint.

Use of exec detected.
Security

Line: 35
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b102_exec_used.html

              
    # Load the generated parser class.
    ns: Dict[str, Any] = {}
    exec(out.getvalue(), ns)
    return ns["GeneratedParser"]


def run_parser(file: IO[bytes], parser_class: Type[Parser], *, verbose: bool = False) -> Any:
    # Run a parser on a file (stream).

            

Reported by Bandit.

Missing module docstring
Error

Line: 1 Column: 1

              import importlib.util
import io
import os
import pathlib
import sys
import textwrap
import tokenize
import token


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 27 Column: 1

              }


def generate_parser(grammar: Grammar) -> Type[Parser]:
    # Generate a parser.
    out = io.StringIO()
    genr = PythonParserGenerator(grammar, out)
    genr.generate("<string>")


            

Reported by Pylint.

Variable name "ns" doesn't conform to snake_case naming style
Error

Line: 34 Column: 5

                  genr.generate("<string>")

    # Load the generated parser class.
    ns: Dict[str, Any] = {}
    exec(out.getvalue(), ns)
    return ns["GeneratedParser"]


def run_parser(file: IO[bytes], parser_class: Type[Parser], *, verbose: bool = False) -> Any:

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 39 Column: 1

                  return ns["GeneratedParser"]


def run_parser(file: IO[bytes], parser_class: Type[Parser], *, verbose: bool = False) -> Any:
    # Run a parser on a file (stream).
    tokenizer = Tokenizer(tokenize.generate_tokens(file.readline))  # type: ignore # typeshed issue #3515
    parser = parser_class(tokenizer, verbose=verbose)
    result = parser.start()
    if result is None:

            

Reported by Pylint.

Line too long (105/100)
Error

Line: 41 Column: 1

              
def run_parser(file: IO[bytes], parser_class: Type[Parser], *, verbose: bool = False) -> Any:
    # Run a parser on a file (stream).
    tokenizer = Tokenizer(tokenize.generate_tokens(file.readline))  # type: ignore # typeshed issue #3515
    parser = parser_class(tokenizer, verbose=verbose)
    result = parser.start()
    if result is None:
        raise parser.make_syntax_error("invalid syntax")
    return result

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 49 Column: 1

                  return result


def parse_string(
    source: str, parser_class: Type[Parser], *, dedent: bool = True, verbose: bool = False
) -> Any:
    # Run the parser on a string.
    if dedent:
        source = textwrap.dedent(source)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 59 Column: 1

                  return run_parser(file, parser_class, verbose=verbose)  # type: ignore # typeshed issue #3515


def make_parser(source: str) -> Type[Parser]:
    # Combine parse_string() and generate_parser().
    grammar = parse_string(source, GrammarParser)
    return generate_parser(grammar)



            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 69
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                  """Import a python module from a path"""

    spec = importlib.util.spec_from_file_location(full_name, path)
    assert spec is not None
    mod = importlib.util.module_from_spec(spec)

    # We assume this is not None and has an exec_module() method.
    # See https://docs.python.org/3/reference/import.html?highlight=exec_module#loading
    loader = cast(Any, spec.loader)

            

Reported by Bandit.

Tools/scripts/generate_opcode_h.py
16 issues
Unused variable 'i'
Error

Line: 38 Column: 9

                  for op in ops:
        bits |= 1<<op
    out.write(f"static uint32_t {name}[8] = {{\n")
    for i in range(8):
        out.write(f"    {bits & UINT32_MASK}U,\n")
        bits >>= 32
    assert bits == 0
    out.write(f"}};\n")


            

Reported by Pylint.

Using an f-string that does not have any interpolated variables
Error

Line: 42 Column: 15

                      out.write(f"    {bits & UINT32_MASK}U,\n")
        bits >>= 32
    assert bits == 0
    out.write(f"}};\n")

def main(opcode_py, outfile='Include/opcode.h'):
    opcode = {}
    if hasattr(tokenize, 'open'):
        fp = tokenize.open(opcode_py)   # Python 3.2+

            

Reported by Pylint.

Use of exec detected.
Security

Line: 52
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b102_exec_used.html

                      fp = open(opcode_py)            # Python 2.7
    with fp:
        code = fp.read()
    exec(code, opcode)
    opmap = opcode['opmap']
    hasjrel = opcode['hasjrel']
    hasjabs = opcode['hasjabs']
    used = [ False ] * 256
    next_op = 1

            

Reported by Bandit.

Use of exec
Error

Line: 52 Column: 5

                      fp = open(opcode_py)            # Python 2.7
    with fp:
        code = fp.read()
    exec(code, opcode)
    opmap = opcode['opmap']
    hasjrel = opcode['hasjrel']
    hasjabs = opcode['hasjabs']
    used = [ False ] * 256
    next_op = 1

            

Reported by Pylint.

Unused variable 'hasjrel'
Error

Line: 54 Column: 5

                      code = fp.read()
    exec(code, opcode)
    opmap = opcode['opmap']
    hasjrel = opcode['hasjrel']
    hasjabs = opcode['hasjabs']
    used = [ False ] * 256
    next_op = 1
    for name, op in opmap.items():
        used[op] = True

            

Reported by Pylint.

Unused variable 'hasjabs'
Error

Line: 55 Column: 5

                  exec(code, opcode)
    opmap = opcode['opmap']
    hasjrel = opcode['hasjrel']
    hasjabs = opcode['hasjabs']
    used = [ False ] * 256
    next_op = 1
    for name, op in opmap.items():
        used[op] = True
    with open(outfile, 'w') as fobj:

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              # This script generates the opcode.h header file.

import sys
import tokenize

header = """
/* Auto-generated by Tools/scripts/generate_opcode_h.py from Lib/opcode.py */
#ifndef Py_OPCODE_H
#define Py_OPCODE_H

            

Reported by Pylint.

Constant name "header" doesn't conform to UPPER_CASE naming style
Error

Line: 6 Column: 1

              import sys
import tokenize

header = """
/* Auto-generated by Tools/scripts/generate_opcode_h.py from Lib/opcode.py */
#ifndef Py_OPCODE_H
#define Py_OPCODE_H
#ifdef __cplusplus
extern "C" {

            

Reported by Pylint.

Constant name "footer" doesn't conform to UPPER_CASE naming style
Error

Line: 18 Column: 1

                  /* Instruction opcodes for compiled code */
""".lstrip()

footer = """
#define HAS_ARG(op) ((op) >= HAVE_ARGUMENT)

/* Reserve some bytecodes for internal use in the compiler.
 * The value of 240 is arbitrary. */
#define IS_ARTIFICIAL(op) ((op) > 240)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 33 Column: 1

              
UINT32_MASK = (1<<32)-1

def write_int_array_from_ops(name, ops, out):
    bits = 0
    for op in ops:
        bits |= 1<<op
    out.write(f"static uint32_t {name}[8] = {{\n")
    for i in range(8):

            

Reported by Pylint.

Tools/scripts/generate_stdlib_module_names.py
15 issues
Using subprocess.run without explicitly set `check` is not recommended.
Error

Line: 114 Column: 12

              # Use the "./Programs/_testembed list_frozen" command.
def list_frozen(names):
    args = [TEST_EMBED, 'list_frozen']
    proc = subprocess.run(args, stdout=subprocess.PIPE, text=True)
    exitcode = proc.returncode
    if exitcode:
        cmd = ' '.join(args)
        print(f"{cmd} failed with exitcode {exitcode}")
        sys.exit(exitcode)

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              # This script lists the names of standard library modules
# to update Python/stdlib_mod_names.h
import os.path
import re
import subprocess
import sys
import sysconfig



            

Reported by Pylint.

Consider possible security implications associated with subprocess module.
Security blacklist

Line: 5
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_imports.html#b404-import-subprocess

              # to update Python/stdlib_mod_names.h
import os.path
import re
import subprocess
import sys
import sysconfig


SRC_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))

            

Reported by Bandit.

Missing function or method docstring
Error

Line: 56 Column: 1

              

# Pure Python modules (Lib/*.py)
def list_python_modules(names):
    for filename in os.listdir(STDLIB_PATH):
        if not filename.endswith(".py"):
            continue
        name = filename.removesuffix(".py")
        names.add(name)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 65 Column: 1

              

# Packages in Lib/
def list_packages(names):
    for name in os.listdir(STDLIB_PATH):
        if name in IGNORE:
            continue
        package_path = os.path.join(STDLIB_PATH, name)
        if not os.path.isdir(package_path):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 78 Column: 1

              

# Extension modules built by setup.py
def list_setup_extensions(names):
    cmd = [sys.executable, SETUP_PY, "-q", "build", "--list-module-names"]
    output = subprocess.check_output(cmd)
    output = output.decode("utf8")
    extensions = output.splitlines()
    names |= set(extensions)

            

Reported by Pylint.

subprocess call - check for execution of untrusted input.
Security injection

Line: 80
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b603_subprocess_without_shell_equals_true.html

              # Extension modules built by setup.py
def list_setup_extensions(names):
    cmd = [sys.executable, SETUP_PY, "-q", "build", "--list-module-names"]
    output = subprocess.check_output(cmd)
    output = output.decode("utf8")
    extensions = output.splitlines()
    names |= set(extensions)



            

Reported by Bandit.

Missing function or method docstring
Error

Line: 87 Column: 1

              

# Built-in and extension modules built by Modules/Setup
def list_modules_setup_extensions(names):
    assign_var = re.compile("^[A-Z]+=")

    with open(MODULES_SETUP, encoding="utf-8") as modules_fp:
        for line in modules_fp:
            # Strip comment

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 112 Column: 1

              
# List frozen modules of the PyImport_FrozenModules list (Python/frozen.c).
# Use the "./Programs/_testembed list_frozen" command.
def list_frozen(names):
    args = [TEST_EMBED, 'list_frozen']
    proc = subprocess.run(args, stdout=subprocess.PIPE, text=True)
    exitcode = proc.returncode
    if exitcode:
        cmd = ' '.join(args)

            

Reported by Pylint.

subprocess call - check for execution of untrusted input.
Security injection

Line: 114
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b603_subprocess_without_shell_equals_true.html

              # Use the "./Programs/_testembed list_frozen" command.
def list_frozen(names):
    args = [TEST_EMBED, 'list_frozen']
    proc = subprocess.run(args, stdout=subprocess.PIPE, text=True)
    exitcode = proc.returncode
    if exitcode:
        cmd = ' '.join(args)
        print(f"{cmd} failed with exitcode {exitcode}")
        sys.exit(exitcode)

            

Reported by Bandit.

Tools/scripts/nm2def.py
15 issues
Starting a process with a shell, possible injection detected, security issue.
Security injection

Line: 45
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html

              
def symbols(lib=PYTHONLIB,types=('T','C','D')):

    with os.popen(NM % lib) as pipe:
        lines = pipe.readlines()
    lines = [s.strip() for s in lines]
    symbols = {}
    for line in lines:
        if len(line) == 0 or ':' in line:

            

Reported by Bandit.

Redefining name 'symbols' from outer scope (line 43)
Error

Line: 48 Column: 5

                  with os.popen(NM % lib) as pipe:
        lines = pipe.readlines()
    lines = [s.strip() for s in lines]
    symbols = {}
    for line in lines:
        if len(line) == 0 or ':' in line:
            continue
        items = line.split()
        if len(items) != 3:

            

Reported by Pylint.

Redefining built-in 'type'
Error

Line: 55 Column: 18

                      items = line.split()
        if len(items) != 3:
            continue
        address, type, name = items
        if type not in types:
            continue
        symbols[name] = address,type
    return symbols


            

Reported by Pylint.

Redefining name 'symbols' from outer scope (line 43)
Error

Line: 61 Column: 17

                      symbols[name] = address,type
    return symbols

def export_list(symbols):

    data = []
    code = []
    for name,(addr,type) in symbols.items():
        if type in ('C','D'):

            

Reported by Pylint.

Unused variable 'addr'
Error

Line: 65 Column: 15

              
    data = []
    code = []
    for name,(addr,type) in symbols.items():
        if type in ('C','D'):
            data.append('\t'+name)
        else:
            code.append('\t'+name)
    data.sort()

            

Reported by Pylint.

Redefining built-in 'type'
Error

Line: 65 Column: 20

              
    data = []
    code = []
    for name,(addr,type) in symbols.items():
        if type in ('C','D'):
            data.append('\t'+name)
        else:
            code.append('\t'+name)
    data.sort()

            

Reported by Pylint.

Redefining name 'symbols' from outer scope (line 43)
Error

Line: 86 Column: 19

              SPECIALS = (
    )

def filter_Python(symbols,specials=SPECIALS):

    for name in list(symbols.keys()):
        if name[:2] == 'Py' or name[:3] == '_Py':
            pass
        elif name not in specials:

            

Reported by Pylint.

Multiple imports on one line (os, sys)
Error

Line: 37 Column: 1

              option to produce this format (since it is the original v7 Unix format).

"""
import os, sys

PYTHONLIB = 'libpython%d.%d.a' % sys.version_info[:2]
PC_PYTHONLIB = 'Python%d%d.dll' % sys.version_info[:2]
NM = 'nm -p -g %s'                      # For Linux, use "nm -g %s"


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 43 Column: 1

              PC_PYTHONLIB = 'Python%d%d.dll' % sys.version_info[:2]
NM = 'nm -p -g %s'                      # For Linux, use "nm -g %s"

def symbols(lib=PYTHONLIB,types=('T','C','D')):

    with os.popen(NM % lib) as pipe:
        lines = pipe.readlines()
    lines = [s.strip() for s in lines]
    symbols = {}

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 61 Column: 1

                      symbols[name] = address,type
    return symbols

def export_list(symbols):

    data = []
    code = []
    for name,(addr,type) in symbols.items():
        if type in ('C','D'):

            

Reported by Pylint.

Python/getargs.c
15 issues
char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 258 Column: 5 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

              vgetargs1_impl(PyObject *compat_args, PyObject *const *stack, Py_ssize_t nargs, const char *format,
               va_list *p_va, int flags)
{
    char msgbuf[256];
    int levels[32];
    const char *fname = NULL;
    const char *message = NULL;
    int min = -1;
    int max = 0;

            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 442 Column: 5 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

              seterror(Py_ssize_t iarg, const char *msg, int *levels, const char *fname,
         const char *message)
{
    char buf[512];
    int i;
    char *p = buf;

    if (PyErr_Occurred())
        return;

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 1187 Column: 13 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                                  RETURN_ERR_OCCURRED;
                }
            }
            memcpy(*buffer, ptr, size+1);

            *psize = size;
        }
        else {
            /* Using a 0-terminated buffer:

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 1222 Column: 13 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                              return converterr("(cleanup problem)",
                                arg, msgbuf, bufsize);
            }
            memcpy(*buffer, ptr, size+1);
        }
        Py_DECREF(s);
        break;
    }


            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 1577 Column: 5 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

              vgetargskeywords(PyObject *args, PyObject *kwargs, const char *format,
                 char **kwlist, va_list *p_va, int flags)
{
    char msgbuf[512];
    int levels[32];
    const char *fname, *msg, *custom_msg;
    int min = INT_MAX;
    int max = INT_MAX;
    int i, pos, len;

            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 2012 Column: 5 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

                                        va_list *p_va, int flags)
{
    PyObject *kwtuple;
    char msgbuf[512];
    int levels[32];
    const char *format;
    const char *msg;
    PyObject *keyword;
    int i, pos, len;

            

Reported by FlawFinder.

strlen - Does not handle strings that are not \0-terminated; if given one it may perform an over-read (it could cause a crash if unprotected)
Security

Line: 451 Column: 18 CWE codes: 126

                  else if (message == NULL) {
        if (fname != NULL) {
            PyOS_snprintf(p, sizeof(buf), "%.200s() ", fname);
            p += strlen(p);
        }
        if (iarg != 0) {
            PyOS_snprintf(p, sizeof(buf) - (p - buf),
                          "argument %zd", iarg);
            i = 0;

            

Reported by FlawFinder.

strlen - Does not handle strings that are not \0-terminated; if given one it may perform an over-read (it could cause a crash if unprotected)
Security

Line: 457 Column: 18 CWE codes: 126

                          PyOS_snprintf(p, sizeof(buf) - (p - buf),
                          "argument %zd", iarg);
            i = 0;
            p += strlen(p);
            while (i < 32 && levels[i] > 0 && (int)(p-buf) < 220) {
                PyOS_snprintf(p, sizeof(buf) - (p - buf),
                              ", item %d", levels[i]-1);
                p += strlen(p);
                i++;

            

Reported by FlawFinder.

strlen - Does not handle strings that are not \0-terminated; if given one it may perform an over-read (it could cause a crash if unprotected)
Security

Line: 461 Column: 22 CWE codes: 126

                          while (i < 32 && levels[i] > 0 && (int)(p-buf) < 220) {
                PyOS_snprintf(p, sizeof(buf) - (p - buf),
                              ", item %d", levels[i]-1);
                p += strlen(p);
                i++;
            }
        }
        else {
            PyOS_snprintf(p, sizeof(buf) - (p - buf), "argument");

            

Reported by FlawFinder.

strlen - Does not handle strings that are not \0-terminated; if given one it may perform an over-read (it could cause a crash if unprotected)
Security

Line: 467 Column: 18 CWE codes: 126

                      }
        else {
            PyOS_snprintf(p, sizeof(buf) - (p - buf), "argument");
            p += strlen(p);
        }
        PyOS_snprintf(p, sizeof(buf) - (p - buf), " %.256s", msg);
        message = buf;
    }
    if (msg[0] == '(') {

            

Reported by FlawFinder.