The following issues were found

Modules/expat/xmlparse.c
24 issues
system - This causes a new program to execute and is difficult to use safely
Security

Line: 113 Column: 18 CWE codes: 78
Suggestion: try using a library call that implements the same functionality if available

                  XML_POOR_ENTROPY; you have been warned. \
    \
    If you have reasons to patch this detection code away or need changes \
    to the build system, please open a bug.  Thank you!
#endif

#ifdef XML_UNICODE
#  define XML_ENCODE_MAX XML_UTF16_ENCODE_MAX
#  define XmlConvert XmlUtf16Convert

            

Reported by FlawFinder.

getenv - Environment variables are untrustable input if they can be set by an attacker. They can have any content and length, and the same variable can be set more than once
Security

Line: 792 Column: 43 CWE codes: 807 20
Suggestion: Check environment variables carefully before using them

              
static unsigned long
ENTROPY_DEBUG(const char *label, unsigned long entropy) {
  const char *const EXPAT_ENTROPY_DEBUG = getenv("EXPAT_ENTROPY_DEBUG");
  if (EXPAT_ENTROPY_DEBUG && ! strcmp(EXPAT_ENTROPY_DEBUG, "1")) {
    fprintf(stderr, "Entropy: %s --> 0x%0*lx (%lu bytes)\n", label,
            (int)sizeof(entropy) * 2, entropy, (unsigned long)sizeof(entropy));
  }
  return entropy;

            

Reported by FlawFinder.

open - Check when opening files - can an attacker redirect it (via symlinks), force the opening of special file type (e.g., device files), move things around to create a race condition, control its ancestors, or change its contents?
Security

Line: 113 Column: 33 CWE codes: 362

                  XML_POOR_ENTROPY; you have been warned. \
    \
    If you have reasons to patch this detection code away or need changes \
    to the build system, please open a bug.  Thank you!
#endif

#ifdef XML_UNICODE
#  define XML_ENCODE_MAX XML_UTF16_ENCODE_MAX
#  define XmlConvert XmlUtf16Convert

            

Reported by FlawFinder.

open - Check when opening files - can an attacker redirect it (via symlinks), force the opening of special file type (e.g., device files), move things around to create a race condition, control its ancestors, or change its contents?
Security

Line: 274 Column: 12 CWE codes: 362

                const XML_Char *base;
  const XML_Char *publicId;
  const XML_Char *notation;
  XML_Bool open;
  XML_Bool is_param;
  XML_Bool is_internal; /* true if declared in internal subset outside PE */
} ENTITY;

typedef struct {

            

Reported by FlawFinder.

open - Check when opening files - can an attacker redirect it (via symlinks), force the opening of special file type (e.g., device files), move things around to create a race condition, control its ancestors, or change its contents?
Security

Line: 689 Column: 18 CWE codes: 362

                int success = 0; /* full count bytes written? */
  size_t bytesWrittenTotal = 0;

  const int fd = open("/dev/urandom", O_RDONLY);
  if (fd < 0) {
    return 0;
  }

  do {

            

Reported by FlawFinder.

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

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

                      parser->m_buffer = temp;
        parser->m_bufferLim = parser->m_buffer + bytesToAllocate;
      }
      memcpy(parser->m_buffer, end, nLeftOver);
    }
    parser->m_bufferPtr = parser->m_buffer;
    parser->m_bufferEnd = parser->m_buffer + nLeftOver;
    parser->m_positionPtr = parser->m_bufferPtr;
    parser->m_parseEndPtr = parser->m_bufferEnd;

            

Reported by FlawFinder.

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

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

                  if (buff == NULL)
      return XML_STATUS_ERROR;
    else {
      memcpy(buff, s, len);
      return XML_ParseBuffer(parser, len, isFinal);
    }
  }
}


            

Reported by FlawFinder.

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

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

                    parser->m_bufferLim = newBuf + bufferSize;
#ifdef XML_CONTEXT_BYTES
      if (parser->m_bufferPtr) {
        memcpy(newBuf, &parser->m_bufferPtr[-keep],
               EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr)
                   + keep);
        FREE(parser, parser->m_buffer);
        parser->m_buffer = newBuf;
        parser->m_bufferEnd

            

Reported by FlawFinder.

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

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

                    }
#else
      if (parser->m_bufferPtr) {
        memcpy(newBuf, parser->m_bufferPtr,
               EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr));
        FREE(parser, parser->m_buffer);
        parser->m_bufferEnd
            = newBuf
              + EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);

            

Reported by FlawFinder.

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

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

                    tag->bufEnd = temp + bufSize;
      rawNameBuf = temp + nameLen;
    }
    memcpy(rawNameBuf, tag->rawName, tag->rawNameLength);
    tag->rawName = rawNameBuf;
    tag = tag->parent;
  }
  return XML_TRUE;
}

            

Reported by FlawFinder.

Lib/test/test_utf8_mode.py
24 issues
Using subprocess.run without explicitly set `check` is not recommended.
Error

Line: 272 Column: 16

                              f'out.close()')
        cmd = [sys.executable, '-X', 'utf8', '-c', code]
        # The stdout TTY is inherited to the child process
        proc = subprocess.run(cmd, text=True)
        self.assertEqual(proc.returncode, 0, proc)

        # In UTF-8 Mode, device_encoding(fd) returns "UTF-8" if fd is a TTY
        with open(filename, encoding="utf8") as fp:
            out = fp.read().rstrip()

            

Reported by Pylint.

Consider possible security implications associated with subprocess module.
Security blacklist

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

              """

import locale
import subprocess
import sys
import textwrap
import unittest
from test import support
from test.support.script_helper import assert_python_ok, assert_python_failure

            

Reported by Bandit.

Missing class docstring
Error

Line: 19 Column: 1

              POSIX_LOCALES = ('C', 'POSIX')
VXWORKS = (sys.platform == "vxworks")

class UTF8ModeTests(unittest.TestCase):
    DEFAULT_ENV = {
        'PYTHONUTF8': '',
        'PYTHONLEGACYWINDOWSFSENCODING': '',
        'PYTHONCOERCECLOCALE': '0',
    }

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 26 Column: 5

                      'PYTHONCOERCECLOCALE': '0',
    }

    def posix_locale(self):
        loc = locale.setlocale(locale.LC_CTYPE, None)
        return (loc in POSIX_LOCALES)

    def get_output(self, *args, failure=False, **kw):
        kw = dict(self.DEFAULT_ENV, **kw)

            

Reported by Pylint.

Method could be a function
Error

Line: 26 Column: 5

                      'PYTHONCOERCECLOCALE': '0',
    }

    def posix_locale(self):
        loc = locale.setlocale(locale.LC_CTYPE, None)
        return (loc in POSIX_LOCALES)

    def get_output(self, *args, failure=False, **kw):
        kw = dict(self.DEFAULT_ENV, **kw)

            

Reported by Pylint.

Unnecessary parens after 'return' keyword
Error

Line: 28 Column: 1

              
    def posix_locale(self):
        loc = locale.setlocale(locale.LC_CTYPE, None)
        return (loc in POSIX_LOCALES)

    def get_output(self, *args, failure=False, **kw):
        kw = dict(self.DEFAULT_ENV, **kw)
        if failure:
            out = assert_python_failure(*args, **kw)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 30 Column: 5

                      loc = locale.setlocale(locale.LC_CTYPE, None)
        return (loc in POSIX_LOCALES)

    def get_output(self, *args, failure=False, **kw):
        kw = dict(self.DEFAULT_ENV, **kw)
        if failure:
            out = assert_python_failure(*args, **kw)
            out = out[2]
        else:

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 41 Column: 5

                      return out.decode().rstrip("\n\r")

    @unittest.skipIf(MS_WINDOWS, 'Windows has no POSIX locale')
    def test_posix_locale(self):
        code = 'import sys; print(sys.flags.utf8_mode)'

        for loc in POSIX_LOCALES:
            with self.subTest(LC_ALL=loc):
                out = self.get_output('-c', code, LC_ALL=loc)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 49 Column: 5

                              out = self.get_output('-c', code, LC_ALL=loc)
                self.assertEqual(out, '1')

    def test_xoption(self):
        code = 'import sys; print(sys.flags.utf8_mode)'

        out = self.get_output('-X', 'utf8', '-c', code)
        self.assertEqual(out, '1')


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 69 Column: 5

                                                PYTHONLEGACYWINDOWSFSENCODING='1')
            self.assertEqual(out, '0')

    def test_env_var(self):
        code = 'import sys; print(sys.flags.utf8_mode)'

        out = self.get_output('-c', code, PYTHONUTF8='1')
        self.assertEqual(out, '1')


            

Reported by Pylint.

Lib/xml/sax/__init__.py
24 issues
Unable to import '__init__.xmlreader'
Error

Line: 22 Column: 1

              expatreader -- Driver that allows use of the Expat parser with SAX.
"""

from .xmlreader import InputSource
from .handler import ContentHandler, ErrorHandler
from ._exceptions import SAXException, SAXNotRecognizedException, \
                        SAXParseException, SAXNotSupportedException, \
                        SAXReaderNotAvailable


            

Reported by Pylint.

Unable to import '__init__.handler'
Error

Line: 23 Column: 1

              """

from .xmlreader import InputSource
from .handler import ContentHandler, ErrorHandler
from ._exceptions import SAXException, SAXNotRecognizedException, \
                        SAXParseException, SAXNotSupportedException, \
                        SAXReaderNotAvailable



            

Reported by Pylint.

Unable to import '__init__._exceptions'
Error

Line: 24 Column: 1

              
from .xmlreader import InputSource
from .handler import ContentHandler, ErrorHandler
from ._exceptions import SAXException, SAXNotRecognizedException, \
                        SAXParseException, SAXNotSupportedException, \
                        SAXReaderNotAvailable


def parse(source, handler, errorHandler=ErrorHandler()):

            

Reported by Pylint.

Module 'sys' has no 'registry' member
Error

Line: 66 Column: 35

              del os

_key = "python.xml.sax.parser"
if sys.platform[:4] == "java" and sys.registry.containsKey(_key):
    default_parser_list = sys.registry.getProperty(_key).split(",")


def make_parser(parser_list=()):
    """Creates and returns a SAX parser.

            

Reported by Pylint.

Module 'sys' has no 'registry' member
Error

Line: 67 Column: 27

              
_key = "python.xml.sax.parser"
if sys.platform[:4] == "java" and sys.registry.containsKey(_key):
    default_parser_list = sys.registry.getProperty(_key).split(",")


def make_parser(parser_list=()):
    """Creates and returns a SAX parser.


            

Reported by Pylint.

Unable to import 'org.python.core'
Error

Line: 98 Column: 9

              
if sys.platform[ : 4] == "java":
    def _create_parser(parser_name):
        from org.python.core import imp
        drv_module = imp.importName(parser_name, 0, globals())
        return drv_module.create_parser()

else:
    def _create_parser(parser_name):

            

Reported by Pylint.

Redefining name 'sys' from outer scope (line 60)
Error

Line: 82 Column: 13

                      try:
            return _create_parser(parser_name)
        except ImportError:
            import sys
            if parser_name in sys.modules:
                # The parser module was found, but importing it
                # failed unexpectedly, pass this exception through
                raise
        except SAXReaderNotAvailable:

            

Reported by Pylint.

Reimport 'sys' (imported line 60)
Error

Line: 82 Column: 13

                      try:
            return _create_parser(parser_name)
        except ImportError:
            import sys
            if parser_name in sys.modules:
                # The parser module was found, but importing it
                # failed unexpectedly, pass this exception through
                raise
        except SAXReaderNotAvailable:

            

Reported by Pylint.

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

Line: 29 Column: 1

                                      SAXReaderNotAvailable


def parse(source, handler, errorHandler=ErrorHandler()):
    parser = make_parser()
    parser.setContentHandler(handler)
    parser.setErrorHandler(errorHandler)
    parser.parse(source)


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 29 Column: 1

                                      SAXReaderNotAvailable


def parse(source, handler, errorHandler=ErrorHandler()):
    parser = make_parser()
    parser.setContentHandler(handler)
    parser.setErrorHandler(errorHandler)
    parser.parse(source)


            

Reported by Pylint.

PCbuild/prepare_ssl.py
24 issues
Starting a process with a shell, possible injection detected, security issue.
Security injection

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

              
def run_configure(configure, do_script):
    print("perl Configure "+configure+" no-idea no-mdc2")
    os.system("perl Configure "+configure+" no-idea no-mdc2")
    print(do_script)
    os.system(do_script)

def fix_uplink():
    # uplink.c tries to find the OPENSSL_Applink function exported from the current

            

Reported by Bandit.

Starting a process with a shell, possible injection detected, security issue.
Security injection

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

                  print("perl Configure "+configure+" no-idea no-mdc2")
    os.system("perl Configure "+configure+" no-idea no-mdc2")
    print(do_script)
    os.system(do_script)

def fix_uplink():
    # uplink.c tries to find the OPENSSL_Applink function exported from the current
    # executable. However, we export it from _ssl[_d].pyd instead. So we update the
    # module name here before building.

            

Reported by Bandit.

Redefining built-in 'dir'
Error

Line: 69 Column: 5

              

def copy_includes(makefile, suffix):
    dir = 'inc'+suffix+'\\openssl'
    try:
        os.makedirs(dir)
    except OSError:
        pass
    copy_if_different = r'$(PERL) $(SRC_D)\util\copy-if-different.pl'

            

Reported by Pylint.

Unused variable 'script'
Error

Line: 78 Column: 23

                  with open(makefile) as fin:
        for line in fin:
            if copy_if_different in line:
                perl, script, src, dest = line.split()
                if not '$(INCO_D)' in dest:
                    continue
                # We're in the root of the source tree
                src = src.replace('$(SRC_D)', '.').strip('"')
                dest = dest.strip('"').replace('$(INCO_D)', dir)

            

Reported by Pylint.

Unused variable 'perl'
Error

Line: 78 Column: 17

                  with open(makefile) as fin:
        for line in fin:
            if copy_if_different in line:
                perl, script, src, dest = line.split()
                if not '$(INCO_D)' in dest:
                    continue
                # We're in the root of the source tree
                src = src.replace('$(SRC_D)', '.').strip('"')
                dest = dest.strip('"').replace('$(INCO_D)', dir)

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              #! /usr/bin/env python3
# Script for preparing OpenSSL for building on Windows.
# Uses Perl to create nmake makefiles and otherwise prepare the way
# for building on 32 or 64 bit platforms.

# Script originally authored by Mark Hammond.
# Major revisions by:
#   Martin v. Löwis
#   Christian Heimes

            

Reported by Pylint.

Consider possible security implications associated with subprocess module.
Security blacklist

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

              import os
import re
import sys
import subprocess
from shutil import copy

# Find all "foo.exe" files on the PATH.
def find_all_on_path(filename, extras=None):
    entries = os.environ["PATH"].split(os.pathsep)

            

Reported by Bandit.

Missing function or method docstring
Error

Line: 30 Column: 1

              from shutil import copy

# Find all "foo.exe" files on the PATH.
def find_all_on_path(filename, extras=None):
    entries = os.environ["PATH"].split(os.pathsep)
    ret = []
    for p in entries:
        fname = os.path.abspath(os.path.join(p, filename))
        if os.path.isfile(fname) and fname not in ret:

            

Reported by Pylint.

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

Line: 33 Column: 9

              def find_all_on_path(filename, extras=None):
    entries = os.environ["PATH"].split(os.pathsep)
    ret = []
    for p in entries:
        fname = os.path.abspath(os.path.join(p, filename))
        if os.path.isfile(fname) and fname not in ret:
            ret.append(fname)
    if extras:
        for p in extras:

            

Reported by Pylint.

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

Line: 38 Column: 13

                      if os.path.isfile(fname) and fname not in ret:
            ret.append(fname)
    if extras:
        for p in extras:
            fname = os.path.abspath(os.path.join(p, filename))
            if os.path.isfile(fname) and fname not in ret:
                ret.append(fname)
    return ret


            

Reported by Pylint.

Lib/test/test_asdl_parser.py
24 issues
Redefining built-in 'type'
Error

Line: 112 Column: 33

                              for dfn in mod.dfns:
                    self.visit(dfn)

            def visitType(self, type):
                self.visit(type.value)

            def visitSum(self, sum):
                for t in sum.types:
                    self.visit(t)

            

Reported by Pylint.

Redefining built-in 'sum'
Error

Line: 115 Column: 32

                          def visitType(self, type):
                self.visit(type.value)

            def visitSum(self, sum):
                for t in sum.types:
                    self.visit(t)

            def visitConstructor(self, cons):
                for f in cons.fields:

            

Reported by Pylint.

Missing class docstring
Error

Line: 20 Column: 1

              parser_dir = os.path.join(src_base, 'Parser')


class TestAsdlParser(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        # Loads the asdl module dynamically, since it's not in a real importable
        # package.
        # Parses Python.asdl into an ast.Module and run the check on it.

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 47 Column: 5

                      self.mod = TestAsdlParser.mod
        self.types = self.mod.types

    def test_module(self):
        self.assertEqual(self.mod.name, 'Python')
        self.assertIn('stmt', self.types)
        self.assertIn('expr', self.types)
        self.assertIn('mod', self.types)


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 53 Column: 5

                      self.assertIn('expr', self.types)
        self.assertIn('mod', self.types)

    def test_definitions(self):
        defs = self.mod.dfns
        self.assertIsInstance(defs[0], self.asdl.Type)
        self.assertIsInstance(defs[0].value, self.asdl.Sum)

        self.assertIsInstance(self.types['withitem'], self.asdl.Product)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 61 Column: 5

                      self.assertIsInstance(self.types['withitem'], self.asdl.Product)
        self.assertIsInstance(self.types['alias'], self.asdl.Product)

    def test_product(self):
        alias = self.types['alias']
        self.assertEqual(
            str(alias),
            'Product([Field(identifier, name), Field(identifier, asname, opt=True)], '
            '[Field(int, lineno), Field(int, col_offset), '

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 69 Column: 5

                          '[Field(int, lineno), Field(int, col_offset), '
            'Field(int, end_lineno, opt=True), Field(int, end_col_offset, opt=True)])')

    def test_attributes(self):
        stmt = self.types['stmt']
        self.assertEqual(len(stmt.attributes), 4)
        self.assertEqual(repr(stmt.attributes[0]), 'Field(int, lineno)')
        self.assertEqual(repr(stmt.attributes[1]), 'Field(int, col_offset)')
        self.assertEqual(repr(stmt.attributes[2]), 'Field(int, end_lineno, opt=True)')

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 77 Column: 5

                      self.assertEqual(repr(stmt.attributes[2]), 'Field(int, end_lineno, opt=True)')
        self.assertEqual(repr(stmt.attributes[3]), 'Field(int, end_col_offset, opt=True)')

    def test_constructor_fields(self):
        ehandler = self.types['excepthandler']
        self.assertEqual(len(ehandler.types), 1)
        self.assertEqual(len(ehandler.attributes), 4)

        cons = ehandler.types[0]

            

Reported by Pylint.

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

Line: 86 Column: 9

                      self.assertIsInstance(cons, self.asdl.Constructor)
        self.assertEqual(len(cons.fields), 3)

        f0 = cons.fields[0]
        self.assertEqual(f0.type, 'expr')
        self.assertEqual(f0.name, 'type')
        self.assertTrue(f0.opt)

        f1 = cons.fields[1]

            

Reported by Pylint.

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

Line: 91 Column: 9

                      self.assertEqual(f0.name, 'type')
        self.assertTrue(f0.opt)

        f1 = cons.fields[1]
        self.assertEqual(f1.type, 'identifier')
        self.assertEqual(f1.name, 'name')
        self.assertTrue(f1.opt)

        f2 = cons.fields[2]

            

Reported by Pylint.

Lib/test/test_imghdr.py
24 issues
No value for argument 'file' in function call
Error

Line: 82 Column: 13

              
    def test_bad_args(self):
        with self.assertRaises(TypeError):
            imghdr.what()
        with self.assertRaises(AttributeError):
            imghdr.what(None)
        with self.assertRaises(TypeError):
            imghdr.what(self.testfile, 1)
        with self.assertRaises(AttributeError):

            

Reported by Pylint.

Unused argument 'file'
Error

Line: 63 Column: 27

                              self.assertEqual(imghdr.what(pathlib.Path(filename)), expected)

    def test_register_test(self):
        def test_jumbo(h, file):
            if h.startswith(b'eggs'):
                return 'ham'
        imghdr.tests.append(test_jumbo)
        self.addCleanup(imghdr.tests.pop)
        self.assertEqual(imghdr.what(None, b'eggs'), 'ham')

            

Reported by Pylint.

Unused variable 'cm'
Error

Line: 121 Column: 47

                  def test_closed_file(self):
        stream = open(self.testfile, 'rb')
        stream.close()
        with self.assertRaises(ValueError) as cm:
            imghdr.what(stream)
        stream = io.BytesIO(self.testdata)
        stream.close()
        with self.assertRaises(ValueError) as cm:
            imghdr.what(stream)

            

Reported by Pylint.

Unused variable 'cm'
Error

Line: 139 Column: 48

                      with open(TESTFN, 'wb') as stream:
            stream.write(self.testdata)
            stream.seek(0)
            with self.assertRaises(OSError) as cm:
                imghdr.what(stream)

if __name__ == '__main__':
    unittest.main()

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import imghdr
import io
import os
import pathlib
import unittest
import warnings
from test.support import findfile
from test.support.os_helper import TESTFN, unlink


            

Reported by Pylint.

Missing class docstring
Error

Line: 28 Column: 1

                  ('python.exr', 'exr'),
)

class UnseekableIO(io.FileIO):
    def tell(self):
        raise io.UnsupportedOperation

    def seek(self, *args, **kwargs):
        raise io.UnsupportedOperation

            

Reported by Pylint.

Missing class docstring
Error

Line: 35 Column: 1

                  def seek(self, *args, **kwargs):
        raise io.UnsupportedOperation

class TestImghdr(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.testfile = findfile('python.png', subdir='imghdrdata')
        with open(cls.testfile, 'rb') as stream:
            cls.testdata = stream.read()

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 45 Column: 5

                  def tearDown(self):
        unlink(TESTFN)

    def test_data(self):
        for filename, expected in TEST_FILES:
            filename = findfile(filename, subdir='imghdrdata')
            self.assertEqual(imghdr.what(filename), expected)
            with open(filename, 'rb') as stream:
                self.assertEqual(imghdr.what(stream), expected)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 56 Column: 5

                          self.assertEqual(imghdr.what(None, data), expected)
            self.assertEqual(imghdr.what(None, bytearray(data)), expected)

    def test_pathlike_filename(self):
        for filename, expected in TEST_FILES:
            with self.subTest(filename=filename):
                filename = findfile(filename, subdir='imghdrdata')
                self.assertEqual(imghdr.what(pathlib.Path(filename)), expected)


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 62 Column: 5

                              filename = findfile(filename, subdir='imghdrdata')
                self.assertEqual(imghdr.what(pathlib.Path(filename)), expected)

    def test_register_test(self):
        def test_jumbo(h, file):
            if h.startswith(b'eggs'):
                return 'ham'
        imghdr.tests.append(test_jumbo)
        self.addCleanup(imghdr.tests.pop)

            

Reported by Pylint.

Lib/runpy.py
24 issues
TODO: Replace these helpers with importlib._bootstrap_external functions.
Error

Line: 62 Column: 3

                      self.value = self._sentinel
        sys.argv[0] = self._saved_value

# TODO: Replace these helpers with importlib._bootstrap_external functions.
def _run_code(code, run_globals, init_globals=None,
              mod_name=None, mod_spec=None,
              pkg_name=None, script_name=None):
    """Helper to run code in nominated namespace"""
    if init_globals is not None:

            

Reported by Pylint.

Use of exec
Error

Line: 86 Column: 5

                                     __loader__ = loader,
                       __package__ = pkg_name,
                       __spec__ = mod_spec)
    exec(code, run_globals)
    return run_globals

def _run_module_code(code, init_globals=None,
                    mod_name=None, mod_spec=None,
                    pkg_name=None, script_name=None):

            

Reported by Pylint.

Use of exec detected.
Security

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

                                     __loader__ = loader,
                       __package__ = pkg_name,
                       __spec__ = mod_spec)
    exec(code, run_globals)
    return run_globals

def _run_module_code(code, init_globals=None,
                    mod_name=None, mod_spec=None,
                    pkg_name=None, script_name=None):

            

Reported by Bandit.

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

Line: 150 Column: 13

                      except error as e:
            if mod_name not in sys.modules:
                raise  # No module loaded; being a package is irrelevant
            raise error(("%s; %r is a package and cannot " +
                               "be directly executed") %(e, mod_name))
    loader = spec.loader
    if loader is None:
        raise error("%r is a namespace package and cannot be executed"
                                                                 % mod_name)

            

Reported by Pylint.

XXX ncoghlan: Should this be documented and made public?
Error

Line: 167 Column: 3

              class _Error(Exception):
    """Error that _run_module_as_main() should report without a traceback"""

# XXX ncoghlan: Should this be documented and made public?
# (Current thoughts: don't repeat the mistake that lead to its
# creation when run_module() no longer met the needs of
# mainmodule.c, but couldn't be changed because it was public)
def _run_module_as_main(mod_name, alter_argv=True):
    """Runs the designated module in the __main__ namespace

            

Reported by Pylint.

Unused argument 'run_name'
Error

Line: 233 Column: 25

                      sys.modules[main_name] = saved_main


def _get_code_from_file(run_name, fname):
    # Check for a compiled file first
    from pkgutil import read_code
    decoded_path = os.path.abspath(os.fsdecode(fname))
    with io.open_code(decoded_path) as f:
        code = read_code(f)

            

Reported by Pylint.

Unused variable 'mod_name'
Error

Line: 282 Column: 13

                          # have no choice and we have to remove it even while we read the
            # code. If we don't do this, a __loader__ attribute in the
            # existing __main__ module may prevent location of the new module.
            mod_name, mod_spec, code = _get_main_module_details()
            with _TempModule(run_name) as temp_module, \
                 _ModifiedArgv0(path_name):
                mod_globals = temp_module.module.__dict__
                return _run_code(code, mod_globals, init_globals,
                                    run_name, mod_spec, pkg_name).copy()

            

Reported by Pylint.

Class '_TempModule' inherits from object, can be safely removed from bases in python3
Error

Line: 24 Column: 1

                  "run_module", "run_path",
]

class _TempModule(object):
    """Temporarily replace a module in sys.modules with an empty namespace"""
    def __init__(self, mod_name):
        self.mod_name = mod_name
        self.module = types.ModuleType(mod_name)
        self._saved_module = []

            

Reported by Pylint.

Class '_ModifiedArgv0' inherits from object, can be safely removed from bases in python3
Error

Line: 47 Column: 1

                          del sys.modules[self.mod_name]
        self._saved_module = []

class _ModifiedArgv0(object):
    def __init__(self, value):
        self.value = value
        self._saved_value = self._sentinel = object()

    def __enter__(self):

            

Reported by Pylint.

Too many arguments (7/5)
Error

Line: 63 Column: 1

                      sys.argv[0] = self._saved_value

# TODO: Replace these helpers with importlib._bootstrap_external functions.
def _run_code(code, run_globals, init_globals=None,
              mod_name=None, mod_spec=None,
              pkg_name=None, script_name=None):
    """Helper to run code in nominated namespace"""
    if init_globals is not None:
        run_globals.update(init_globals)

            

Reported by Pylint.

Lib/test/test__locale.py
24 issues
Redefining built-in 'min'
Error

Line: 13 Column: 10

              from platform import uname

if uname().system == "Darwin":
    maj, min, mic = [int(part) for part in uname().release.split(".")]
    if (maj, min, mic) < (8, 0, 0):
        raise unittest.SkipTest("locale support broken for OS X < 10.4")

candidate_locales = ['es_UY', 'fr_FR', 'fi_FI', 'es_CO', 'pt_PT', 'it_IT',
    'et_EE', 'es_PY', 'no_NO', 'nl_NL', 'lv_LV', 'el_GR', 'be_BY', 'fr_BE',

            

Reported by Pylint.

Using the global statement
Error

Line: 30 Column: 5

                  'ru_RU.KOI8-R', 'ko_KR.eucKR']

def setUpModule():
    global candidate_locales
    # Issue #13441: Skip some locales (e.g. cs_CZ and hu_HU) on Solaris to
    # workaround a mbstowcs() bug. For example, on Solaris, the hu_HU locale uses
    # the locale encoding ISO-8859-2, the thousands separator is b'\xA0' and it is
    # decoded as U+30000020 (an invalid character) by mbstowcs().
    if sys.platform == 'sunos5':

            

Reported by Pylint.

Catching too general exception Exception
Error

Line: 47 Column: 24

                              encoding = locale.getpreferredencoding(False)
                try:
                    localeconv()
                except Exception as err:
                    print("WARNING: Skip locale %s (encoding %s): [%s] %s"
                        % (loc, encoding, type(err), err))
                else:
                    locales.append(loc)
            candidate_locales = locales

            

Reported by Pylint.

Use of possibly insecure function - consider using safer ast.literal_eval.
Security blacklist

Line: 184
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b307-eval

                          if loc == 'eu_ES' and localeconv()['decimal_point'] == "' ":
                continue

            self.assertEqual(int(eval('3.14') * 100), 314,
                                "using eval('3.14') failed for %s" % loc)
            self.assertEqual(int(float('3.14') * 100), 314,
                                "using float('3.14') failed for %s" % loc)
            if localeconv()['decimal_point'] != '.':
                self.assertRaises(ValueError, float,

            

Reported by Bandit.

Use of eval
Error

Line: 184 Column: 34

                          if loc == 'eu_ES' and localeconv()['decimal_point'] == "' ":
                continue

            self.assertEqual(int(eval('3.14') * 100), 314,
                                "using eval('3.14') failed for %s" % loc)
            self.assertEqual(int(float('3.14') * 100), 314,
                                "using float('3.14') failed for %s" % loc)
            if localeconv()['decimal_point'] != '.':
                self.assertRaises(ValueError, float,

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from _locale import (setlocale, LC_ALL, LC_CTYPE, LC_NUMERIC, localeconv, Error)
try:
    from _locale import (RADIXCHAR, THOUSEP, nl_langinfo)
except ImportError:
    nl_langinfo = None

import locale
import sys
import unittest

            

Reported by Pylint.

standard import "import locale" should be placed before "from _locale import setlocale, LC_ALL, LC_CTYPE, LC_NUMERIC, localeconv, Error"
Error

Line: 7 Column: 1

              except ImportError:
    nl_langinfo = None

import locale
import sys
import unittest
from platform import uname

if uname().system == "Darwin":

            

Reported by Pylint.

standard import "import sys" should be placed before "from _locale import setlocale, LC_ALL, LC_CTYPE, LC_NUMERIC, localeconv, Error"
Error

Line: 8 Column: 1

                  nl_langinfo = None

import locale
import sys
import unittest
from platform import uname

if uname().system == "Darwin":
    maj, min, mic = [int(part) for part in uname().release.split(".")]

            

Reported by Pylint.

standard import "import unittest" should be placed before "from _locale import setlocale, LC_ALL, LC_CTYPE, LC_NUMERIC, localeconv, Error"
Error

Line: 9 Column: 1

              
import locale
import sys
import unittest
from platform import uname

if uname().system == "Darwin":
    maj, min, mic = [int(part) for part in uname().release.split(".")]
    if (maj, min, mic) < (8, 0, 0):

            

Reported by Pylint.

standard import "from platform import uname" should be placed before "from _locale import setlocale, LC_ALL, LC_CTYPE, LC_NUMERIC, localeconv, Error"
Error

Line: 10 Column: 1

              import locale
import sys
import unittest
from platform import uname

if uname().system == "Darwin":
    maj, min, mic = [int(part) for part in uname().release.split(".")]
    if (maj, min, mic) < (8, 0, 0):
        raise unittest.SkipTest("locale support broken for OS X < 10.4")

            

Reported by Pylint.

Lib/test/test_baseexception.py
24 issues
Catching too general exception Exception
Error

Line: 138 Column: 16

                              pass
        except TypeError:
            pass
        except Exception:
            self.fail("TypeError expected when catching %s" % type(object_))

        try:
            try:
                raise Exception

            

Reported by Pylint.

Catching too general exception Exception
Error

Line: 148 Column: 16

                              pass
        except TypeError:
            return
        except Exception:
            self.fail("TypeError expected when catching %s as specified in a "
                        "tuple" % type(object_))

    def test_raise_new_style_non_exception(self):
        # You cannot raise a new-style class that does not inherit from

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import unittest
import builtins
import os
from platform import system as platform_system


class ExceptionClassTests(unittest.TestCase):

    """Tests for anything relating to exception objects themselves (e.g.,

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 12 Column: 5

                  """Tests for anything relating to exception objects themselves (e.g.,
    inheritance hierarchy)"""

    def test_builtins_new_style(self):
        self.assertTrue(issubclass(Exception, object))

    def verify_instance_interface(self, ins):
        for attr in ("args", "__str__", "__repr__"):
            self.assertTrue(hasattr(ins, attr),

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 15 Column: 5

                  def test_builtins_new_style(self):
        self.assertTrue(issubclass(Exception, object))

    def verify_instance_interface(self, ins):
        for attr in ("args", "__str__", "__repr__"):
            self.assertTrue(hasattr(ins, attr),
                    "%s missing %s attribute" %
                        (ins.__class__.__name__, attr))


            

Reported by Pylint.

Too many statements (51/50)
Error

Line: 21 Column: 5

                                  "%s missing %s attribute" %
                        (ins.__class__.__name__, attr))

    def test_inheritance(self):
        # Make sure the inheritance hierarchy matches the documentation
        exc_set = set()
        for object_ in builtins.__dict__.values():
            try:
                if issubclass(object_, BaseException):

            

Reported by Pylint.

Too many branches (15/12)
Error

Line: 21 Column: 5

                                  "%s missing %s attribute" %
                        (ins.__class__.__name__, attr))

    def test_inheritance(self):
        # Make sure the inheritance hierarchy matches the documentation
        exc_set = set()
        for object_ in builtins.__dict__.values():
            try:
                if issubclass(object_, BaseException):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 21 Column: 5

                                  "%s missing %s attribute" %
                        (ins.__class__.__name__, attr))

    def test_inheritance(self):
        # Make sure the inheritance hierarchy matches the documentation
        exc_set = set()
        for object_ in builtins.__dict__.values():
            try:
                if issubclass(object_, BaseException):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 85 Column: 5

              
    interface_tests = ("length", "args", "str", "repr")

    def interface_test_driver(self, results):
        for test_name, (given, expected) in zip(self.interface_tests, results):
            self.assertEqual(given, expected, "%s: %s != %s" % (test_name,
                given, expected))

    def test_interface_single_arg(self):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 90 Column: 5

                          self.assertEqual(given, expected, "%s: %s != %s" % (test_name,
                given, expected))

    def test_interface_single_arg(self):
        # Make sure interface works properly when given a single argument
        arg = "spam"
        exc = Exception(arg)
        results = ([len(exc.args), 1], [exc.args[0], arg],
                   [str(exc), str(arg)],

            

Reported by Pylint.

Lib/test/test_exception_variations.py
24 issues
No exception type(s) specified
Error

Line: 12 Column: 9

              
        try:
            raise Exception('nyaa!')
        except:
            hit_except = True
        else:
            hit_else = True
        finally:
            hit_finally = True

            

Reported by Pylint.

No exception type(s) specified
Error

Line: 30 Column: 9

              
        try:
            pass
        except:
            hit_except = True
        else:
            hit_else = True
        finally:
            hit_finally = True

            

Reported by Pylint.

No exception type(s) specified
Error

Line: 47 Column: 9

              
        try:
            raise Exception('yarr!')
        except:
            hit_except = True
        finally:
            hit_finally = True

        self.assertTrue(hit_except)

            

Reported by Pylint.

No exception type(s) specified
Error

Line: 61 Column: 9

              
        try:
            pass
        except:
            hit_except = True
        finally:
            hit_finally = True

        self.assertFalse(hit_except)

            

Reported by Pylint.

No exception type(s) specified
Error

Line: 74 Column: 9

              
        try:
            raise Exception('ahoy!')
        except:
            hit_except = True

        self.assertTrue(hit_except)

    def test_try_except_no_exception(self):

            

Reported by Pylint.

No exception type(s) specified
Error

Line: 84 Column: 9

              
        try:
            pass
        except:
            hit_except = True

        self.assertFalse(hit_except)

    def test_try_except_else(self):

            

Reported by Pylint.

No exception type(s) specified
Error

Line: 95 Column: 9

              
        try:
            raise Exception('foo!')
        except:
            hit_except = True
        else:
            hit_else = True

        self.assertFalse(hit_else)

            

Reported by Pylint.

No exception type(s) specified
Error

Line: 109 Column: 9

              
        try:
            pass
        except:
            hit_except = True
        else:
            hit_else = True

        self.assertFalse(hit_except)

            

Reported by Pylint.

No exception type(s) specified
Error

Line: 135 Column: 13

                      try:
            try:
                raise Exception('inner exception')
            except:
                hit_inner_except = True
            finally:
                hit_inner_finally = True
        finally:
            hit_finally = True

            

Reported by Pylint.

No exception type(s) specified
Error

Line: 156 Column: 13

                      try:
            try:
                pass
            except:
                hit_inner_except = True
            else:
                hit_inner_else = True

            raise Exception('outer exception')

            

Reported by Pylint.