The following issues were found

Lib/test/test_bigaddrspace.py
31 issues
Unused variable 'cm'
Error

Line: 37 Column: 54

                      try:
            x = b"x" * (MAX_Py_ssize_t - 128)

            with self.assertRaises(OverflowError) as cm:
                # this statement used a fast path in ceval.c
                x = x + b"x" * 128

            with self.assertRaises(OverflowError) as cm:
                # this statement used a fast path in ceval.c

            

Reported by Pylint.

Unused variable 'cm'
Error

Line: 76 Column: 52

                      try:
            x = "x" * int(MAX_Py_ssize_t // (1.1 * self.unicodesize))

            with self.assertRaises(MemoryError) as cm:
                # this statement uses a fast path in ceval.c
                x = x + x

            with self.assertRaises(MemoryError) as cm:
                # this statement uses a fast path in ceval.c

            

Reported by Pylint.

Missing class docstring
Error

Line: 19 Column: 1

              import sys


class BytesTest(unittest.TestCase):

    @bigaddrspacetest
    def test_concat(self):
        # Allocate a bytestring that's near the maximum size allowed by
        # the address space, and then try to build a new, larger one through

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 22 Column: 5

              class BytesTest(unittest.TestCase):

    @bigaddrspacetest
    def test_concat(self):
        # Allocate a bytestring that's near the maximum size allowed by
        # the address space, and then try to build a new, larger one through
        # concatenation.
        try:
            x = b"x" * (MAX_Py_ssize_t - 128)

            

Reported by Pylint.

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

Line: 27 Column: 13

                      # the address space, and then try to build a new, larger one through
        # concatenation.
        try:
            x = b"x" * (MAX_Py_ssize_t - 128)
            self.assertRaises(OverflowError, operator.add, x, b"x" * 128)
        finally:
            x = None

    @bigaddrspacetest

            

Reported by Pylint.

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

Line: 30 Column: 13

                          x = b"x" * (MAX_Py_ssize_t - 128)
            self.assertRaises(OverflowError, operator.add, x, b"x" * 128)
        finally:
            x = None

    @bigaddrspacetest
    def test_optimized_concat(self):
        try:
            x = b"x" * (MAX_Py_ssize_t - 128)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 33 Column: 5

                          x = None

    @bigaddrspacetest
    def test_optimized_concat(self):
        try:
            x = b"x" * (MAX_Py_ssize_t - 128)

            with self.assertRaises(OverflowError) as cm:
                # this statement used a fast path in ceval.c

            

Reported by Pylint.

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

Line: 35 Column: 13

                  @bigaddrspacetest
    def test_optimized_concat(self):
        try:
            x = b"x" * (MAX_Py_ssize_t - 128)

            with self.assertRaises(OverflowError) as cm:
                # this statement used a fast path in ceval.c
                x = x + b"x" * 128


            

Reported by Pylint.

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

Line: 37 Column: 54

                      try:
            x = b"x" * (MAX_Py_ssize_t - 128)

            with self.assertRaises(OverflowError) as cm:
                # this statement used a fast path in ceval.c
                x = x + b"x" * 128

            with self.assertRaises(OverflowError) as cm:
                # this statement used a fast path in ceval.c

            

Reported by Pylint.

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

Line: 39 Column: 17

              
            with self.assertRaises(OverflowError) as cm:
                # this statement used a fast path in ceval.c
                x = x + b"x" * 128

            with self.assertRaises(OverflowError) as cm:
                # this statement used a fast path in ceval.c
                x +=  b"x" * 128
        finally:

            

Reported by Pylint.

Lib/multiprocessing/heap.py
31 issues
Attempted relative import beyond top-level package
Error

Line: 18 Column: 1

              import tempfile
import threading

from .context import reduction, assert_spawning
from . import util

__all__ = ['BufferWrapper']

#

            

Reported by Pylint.

Attempted relative import beyond top-level package
Error

Line: 19 Column: 1

              import threading

from .context import reduction, assert_spawning
from . import util

__all__ = ['BufferWrapper']

#
# Inheritable class which wraps an mmap, and from which blocks can be allocated

            

Reported by Pylint.

Unable to import '_winapi'
Error

Line: 29 Column: 5

              
if sys.platform == 'win32':

    import _winapi

    class Arena(object):
        """
        A shared memory area backed by anonymous memory (Windows).
        """

            

Reported by Pylint.

Access to a protected member _RandomNameSequence of a client class
Error

Line: 36 Column: 17

                      A shared memory area backed by anonymous memory (Windows).
        """

        _rand = tempfile._RandomNameSequence()

        def __init__(self, size):
            self.size = size
            for i in range(100):
                name = 'pym-%d-%s' % (os.getpid(), next(self._rand))

            

Reported by Pylint.

Unused variable 'i'
Error

Line: 40 Column: 17

              
        def __init__(self, size):
            self.size = size
            for i in range(100):
                name = 'pym-%d-%s' % (os.getpid(), next(self._rand))
                buf = mmap.mmap(-1, size, tagname=name)
                if _winapi.GetLastError() == 0:
                    break
                # We have reopened a preexisting mmap.

            

Reported by Pylint.

XXX Temporarily preventing buildbot failures while determining
Error

Line: 61 Column: 3

                          self.size, self.name = self._state = state
            # Reopen existing mmap
            self.buffer = mmap.mmap(-1, self.size, tagname=self.name)
            # XXX Temporarily preventing buildbot failures while determining
            # XXX the correct long-term fix. See issue 23060
            #assert _winapi.GetLastError() == _winapi.ERROR_ALREADY_EXISTS

else:


            

Reported by Pylint.

XXX the correct long-term fix. See issue 23060
Error

Line: 62 Column: 3

                          # Reopen existing mmap
            self.buffer = mmap.mmap(-1, self.size, tagname=self.name)
            # XXX Temporarily preventing buildbot failures while determining
            # XXX the correct long-term fix. See issue 23060
            #assert _winapi.GetLastError() == _winapi.ERROR_ALREADY_EXISTS

else:

    class Arena(object):

            

Reported by Pylint.

Probable insecure usage of temp file/directory.
Security

Line: 73
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b108_hardcoded_tmp_directory.html

                      """

        if sys.platform == 'linux':
            _dir_candidates = ['/dev/shm']
        else:
            _dir_candidates = []

        def __init__(self, size, fd=-1):
            self.size = size

            

Reported by Bandit.

Unused variable 'stop'
Error

Line: 336 Column: 24

                      util.Finalize(self, BufferWrapper._heap.free, args=(block,))

    def create_memoryview(self):
        (arena, start, stop), size = self._state
        return memoryview(arena.buffer)[start:start+size]

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              #
# Module which supports allocation of memory from an mmap
#
# multiprocessing/heap.py
#
# Copyright (c) 2006-2008, R Oudkerk
# Licensed to PSF under a Contributor Agreement.
#


            

Reported by Pylint.

Lib/test/test_importlib/import_/test___loader__.py
31 issues
Attempted relative import beyond top-level package
Error

Line: 7 Column: 1

              import unittest
import warnings

from .. import util


class SpecLoaderMock:

    def find_spec(self, fullname, path=None, target=None):

            

Reported by Pylint.

Instance of 'SpecLoaderAttributeTests' has no '__import__' member
Error

Line: 27 Column: 22

                  def test___loader__(self):
        loader = SpecLoaderMock()
        with util.uncache('blah'), util.import_state(meta_path=[loader]):
            module = self.__import__('blah')
        self.assertEqual(loader, module.__loader__)


(Frozen_SpecTests,
 Source_SpecTests

            

Reported by Pylint.

Instance of 'SpecLoaderAttributeTests' has no 'assertEqual' member
Error

Line: 28 Column: 9

                      loader = SpecLoaderMock()
        with util.uncache('blah'), util.import_state(meta_path=[loader]):
            module = self.__import__('blah')
        self.assertEqual(loader, module.__loader__)


(Frozen_SpecTests,
 Source_SpecTests
 ) = util.test_both(SpecLoaderAttributeTests, __import__=util.__import__)

            

Reported by Pylint.

Instance of 'LoaderAttributeTests' has no '__import__' member
Error

Line: 59 Column: 26

                          loader = LoaderMock()
            loader.module = module
            with util.uncache('blah'), util.import_state(meta_path=[loader]):
                module = self.__import__('blah')
            self.assertEqual(loader, module.__loader__)

    def test___loader___is_None(self):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", ImportWarning)

            

Reported by Pylint.

Instance of 'LoaderAttributeTests' has no 'assertEqual' member
Error

Line: 60 Column: 13

                          loader.module = module
            with util.uncache('blah'), util.import_state(meta_path=[loader]):
                module = self.__import__('blah')
            self.assertEqual(loader, module.__loader__)

    def test___loader___is_None(self):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", ImportWarning)
            module = types.ModuleType('blah')

            

Reported by Pylint.

Instance of 'LoaderAttributeTests' has no '__import__' member
Error

Line: 70 Column: 35

                          loader = LoaderMock()
            loader.module = module
            with util.uncache('blah'), util.import_state(meta_path=[loader]):
                returned_module = self.__import__('blah')
            self.assertEqual(loader, module.__loader__)


(Frozen_Tests,
 Source_Tests

            

Reported by Pylint.

Instance of 'LoaderAttributeTests' has no 'assertEqual' member
Error

Line: 71 Column: 13

                          loader.module = module
            with util.uncache('blah'), util.import_state(meta_path=[loader]):
                returned_module = self.__import__('blah')
            self.assertEqual(loader, module.__loader__)


(Frozen_Tests,
 Source_Tests
 ) = util.test_both(LoaderAttributeTests, __import__=util.__import__)

            

Reported by Pylint.

Unused argument 'target'
Error

Line: 12 Column: 46

              
class SpecLoaderMock:

    def find_spec(self, fullname, path=None, target=None):
        return machinery.ModuleSpec(fullname, self)

    def create_module(self, spec):
        return None


            

Reported by Pylint.

Unused argument 'path'
Error

Line: 12 Column: 35

              
class SpecLoaderMock:

    def find_spec(self, fullname, path=None, target=None):
        return machinery.ModuleSpec(fullname, self)

    def create_module(self, spec):
        return None


            

Reported by Pylint.

Unused argument 'spec'
Error

Line: 15 Column: 29

                  def find_spec(self, fullname, path=None, target=None):
        return machinery.ModuleSpec(fullname, self)

    def create_module(self, spec):
        return None

    def exec_module(self, module):
        pass


            

Reported by Pylint.

Lib/test/test_epoll.py
31 issues
Unused variable 'addr'
Error

Line: 60 Column: 17

                          self.assertEqual(e.args[0], errno.EINPROGRESS)
        else:
            raise AssertionError("Connect should have raised EINPROGRESS")
        server, addr = self.serverSocket.accept()

        self.connections.extend((client, server))
        return client, server

    def test_create(self):

            

Reported by Pylint.

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

Line: 69 Column: 13

                      try:
            ep = select.epoll(16)
        except OSError as e:
            raise AssertionError(str(e))
        self.assertTrue(ep.fileno() > 0, ep.fileno())
        self.assertTrue(not ep.closed)
        ep.close()
        self.assertTrue(ep.closed)
        self.assertRaises(ValueError, ep.fileno)

            

Reported by Pylint.

Unused variable 'client'
Error

Line: 215 Column: 17

                                        select.EPOLLIN)

    def test_unregister_closed(self):
        server, client = self._connected_pair()
        fd = server.fileno()
        ep = select.epoll(16)
        ep.register(server)

        now = time.monotonic()

            

Reported by Pylint.

Unused variable 'events'
Error

Line: 221 Column: 9

                      ep.register(server)

        now = time.monotonic()
        events = ep.poll(1, 4)
        then = time.monotonic()
        self.assertFalse(then - now > 0.01)

        server.close()


            

Reported by Pylint.

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

Line: 36 Column: 1

              
try:
    select.epoll()
except OSError as e:
    if e.errno == errno.ENOSYS:
        raise unittest.SkipTest("kernel doesn't support epoll()")
    raise

class TestEPoll(unittest.TestCase):

            

Reported by Pylint.

Missing class docstring
Error

Line: 41 Column: 1

                      raise unittest.SkipTest("kernel doesn't support epoll()")
    raise

class TestEPoll(unittest.TestCase):

    def setUp(self):
        self.serverSocket = socket.create_server(('127.0.0.1', 0))
        self.connections = [self.serverSocket]


            

Reported by Pylint.

Attribute name "serverSocket" doesn't conform to snake_case naming style
Error

Line: 44 Column: 9

              class TestEPoll(unittest.TestCase):

    def setUp(self):
        self.serverSocket = socket.create_server(('127.0.0.1', 0))
        self.connections = [self.serverSocket]

    def tearDown(self):
        for skt in self.connections:
            skt.close()

            

Reported by Pylint.

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

Line: 56 Column: 9

                      client.setblocking(False)
        try:
            client.connect(('127.0.0.1', self.serverSocket.getsockname()[1]))
        except OSError as e:
            self.assertEqual(e.args[0], errno.EINPROGRESS)
        else:
            raise AssertionError("Connect should have raised EINPROGRESS")
        server, addr = self.serverSocket.accept()


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 65 Column: 5

                      self.connections.extend((client, server))
        return client, server

    def test_create(self):
        try:
            ep = select.epoll(16)
        except OSError as e:
            raise AssertionError(str(e))
        self.assertTrue(ep.fileno() > 0, ep.fileno())

            

Reported by Pylint.

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

Line: 67 Column: 13

              
    def test_create(self):
        try:
            ep = select.epoll(16)
        except OSError as e:
            raise AssertionError(str(e))
        self.assertTrue(ep.fileno() > 0, ep.fileno())
        self.assertTrue(not ep.closed)
        ep.close()

            

Reported by Pylint.

Tools/scripts/find_recursionlimit.py
31 issues
__init__ method from a non direct base class 'RecursiveBlowup1' is called
Error

Line: 37 Column: 9

              
class RecursiveBlowup1:
    def __init__(self):
        self.__init__()

def test_init():
    return RecursiveBlowup1()

class RecursiveBlowup2:

            

Reported by Pylint.

Dangerous default value {} as argument
Error

Line: 73 Column: 1

              def test_recurse():
    return test_recurse()

def test_cpickle(_cache={}):
    import io
    try:
        import _pickle
    except ImportError:
        print("cannot import _pickle, skipped!")

            

Reported by Pylint.

Missing class docstring
Error

Line: 35 Column: 1

              import sys
import itertools

class RecursiveBlowup1:
    def __init__(self):
        self.__init__()

def test_init():
    return RecursiveBlowup1()

            

Reported by Pylint.

Too few public methods (0/2)
Error

Line: 35 Column: 1

              import sys
import itertools

class RecursiveBlowup1:
    def __init__(self):
        self.__init__()

def test_init():
    return RecursiveBlowup1()

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 39 Column: 1

                  def __init__(self):
        self.__init__()

def test_init():
    return RecursiveBlowup1()

class RecursiveBlowup2:
    def __repr__(self):
        return repr(self)

            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 42 Column: 1

              def test_init():
    return RecursiveBlowup1()

class RecursiveBlowup2:
    def __repr__(self):
        return repr(self)

def test_repr():
    return repr(RecursiveBlowup2())

            

Reported by Pylint.

Missing class docstring
Error

Line: 42 Column: 1

              def test_init():
    return RecursiveBlowup1()

class RecursiveBlowup2:
    def __repr__(self):
        return repr(self)

def test_repr():
    return repr(RecursiveBlowup2())

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 46 Column: 1

                  def __repr__(self):
        return repr(self)

def test_repr():
    return repr(RecursiveBlowup2())

class RecursiveBlowup4:
    def __add__(self, x):
        return x + self

            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 49 Column: 1

              def test_repr():
    return repr(RecursiveBlowup2())

class RecursiveBlowup4:
    def __add__(self, x):
        return x + self

def test_add():
    return RecursiveBlowup4() + RecursiveBlowup4()

            

Reported by Pylint.

Missing class docstring
Error

Line: 49 Column: 1

              def test_repr():
    return repr(RecursiveBlowup2())

class RecursiveBlowup4:
    def __add__(self, x):
        return x + self

def test_add():
    return RecursiveBlowup4() + RecursiveBlowup4()

            

Reported by Pylint.

Tools/scripts/objgraph.py
30 issues
Redefining built-in 'dict'
Error

Line: 41 Column: 11

              # The dictionary maps keys to lists of items.
# If there is no list for the key yet, it is created.
#
def store(dict, key, item):
    if key in dict:
        dict[key].append(item)
    else:
        dict[key] = [item]


            

Reported by Pylint.

Redefining built-in 'list'
Error

Line: 50 Column: 10

              # Return a flattened version of a list of strings: the concatenation
# of its elements with intervening spaces.
#
def flat(list):
    s = ''
    for item in list:
        s = s + ' ' + item
    return s[1:]


            

Reported by Pylint.

Statement seems to have no effect
Error

Line: 73 Column: 35

                          break
        # If you get any output from this line,
        # it is probably caused by an unexpected input line:
        if matcher.search(s) < 0: s; continue # Shouldn't happen
        (ra, rb), (r1a, r1b), (r2a, r2b), (r3a, r3b) = matcher.regs[:4]
        fn, name, type = s[r1a:r1b], s[r3a:r3b], s[r2a:r2b]
        if type in definitions:
            store(def2file, name, fn)
            store(file2def, fn, name)

            

Reported by Pylint.

Unused variable 'rb'
Error

Line: 74 Column: 14

                      # If you get any output from this line,
        # it is probably caused by an unexpected input line:
        if matcher.search(s) < 0: s; continue # Shouldn't happen
        (ra, rb), (r1a, r1b), (r2a, r2b), (r3a, r3b) = matcher.regs[:4]
        fn, name, type = s[r1a:r1b], s[r3a:r3b], s[r2a:r2b]
        if type in definitions:
            store(def2file, name, fn)
            store(file2def, fn, name)
        elif type in externals:

            

Reported by Pylint.

Unused variable 'ra'
Error

Line: 74 Column: 10

                      # If you get any output from this line,
        # it is probably caused by an unexpected input line:
        if matcher.search(s) < 0: s; continue # Shouldn't happen
        (ra, rb), (r1a, r1b), (r2a, r2b), (r3a, r3b) = matcher.regs[:4]
        fn, name, type = s[r1a:r1b], s[r3a:r3b], s[r2a:r2b]
        if type in definitions:
            store(def2file, name, fn)
            store(file2def, fn, name)
        elif type in externals:

            

Reported by Pylint.

Redefining built-in 'type'
Error

Line: 75 Column: 19

                      # it is probably caused by an unexpected input line:
        if matcher.search(s) < 0: s; continue # Shouldn't happen
        (ra, rb), (r1a, r1b), (r2a, r2b), (r3a, r3b) = matcher.regs[:4]
        fn, name, type = s[r1a:r1b], s[r3a:r3b], s[r2a:r2b]
        if type in definitions:
            store(def2file, name, fn)
            store(file2def, fn, name)
        elif type in externals:
            store(file2undef, fn, name)

            

Reported by Pylint.

Unused variable 'void'
Error

Line: 168 Column: 14

                      print('e.g.: nm -o /lib/libc.a | objgraph')
        return 1
    optu = optc = optd = 0
    for opt, void in optlist:
        if opt == '-u':
            optu = 1
        elif opt == '-c':
            optc = 1
        elif opt == '-d':

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              #! /usr/bin/env python3

# objgraph
#
# Read "nm -o" input of a set of libraries or modules and print various
# interesting listings, such as:
#
# - which names are used but not defined in the set (and used where),
# - which names are defined in the set (and where),

            

Reported by Pylint.

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

Line: 29 Column: 1

              
# Types of symbols.
#
definitions = 'TRGDSBAEC'
externals = 'UV'
ignore = 'Nntrgdsbavuc'

# Regular expression to parse "nm -o" output.
#

            

Reported by Pylint.

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

Line: 30 Column: 1

              # Types of symbols.
#
definitions = 'TRGDSBAEC'
externals = 'UV'
ignore = 'Nntrgdsbavuc'

# Regular expression to parse "nm -o" output.
#
matcher = re.compile('(.*):\t?........ (.) (.*)$')

            

Reported by Pylint.

Lib/test/test_readline.py
30 issues
Access to a protected member _READLINE_LIBRARY_VERSION of a client class
Error

Line: 22 Column: 42

              readline = import_module('readline')

if hasattr(readline, "_READLINE_LIBRARY_VERSION"):
    is_editline = ("EditLine wrapper" in readline._READLINE_LIBRARY_VERSION)
else:
    is_editline = (readline.__doc__ and "libedit" in readline.__doc__)


def setUpModule():

            

Reported by Pylint.

Access to a protected member _READLINE_VERSION of a client class
Error

Line: 32 Column: 20

                      # Python implementations other than CPython may not have
        # these private attributes
        if hasattr(readline, "_READLINE_VERSION"):
            print(f"readline version: {readline._READLINE_VERSION:#x}")
            print(f"readline runtime version: {readline._READLINE_RUNTIME_VERSION:#x}")
        if hasattr(readline, "_READLINE_LIBRARY_VERSION"):
            print(f"readline library version: {readline._READLINE_LIBRARY_VERSION!r}")
        print(f"use libedit emulation? {is_editline}")


            

Reported by Pylint.

Access to a protected member _READLINE_RUNTIME_VERSION of a client class
Error

Line: 33 Column: 20

                      # these private attributes
        if hasattr(readline, "_READLINE_VERSION"):
            print(f"readline version: {readline._READLINE_VERSION:#x}")
            print(f"readline runtime version: {readline._READLINE_RUNTIME_VERSION:#x}")
        if hasattr(readline, "_READLINE_LIBRARY_VERSION"):
            print(f"readline library version: {readline._READLINE_LIBRARY_VERSION!r}")
        print(f"use libedit emulation? {is_editline}")



            

Reported by Pylint.

Access to a protected member _READLINE_LIBRARY_VERSION of a client class
Error

Line: 35 Column: 20

                          print(f"readline version: {readline._READLINE_VERSION:#x}")
            print(f"readline runtime version: {readline._READLINE_RUNTIME_VERSION:#x}")
        if hasattr(readline, "_READLINE_LIBRARY_VERSION"):
            print(f"readline library version: {readline._READLINE_LIBRARY_VERSION!r}")
        print(f"use libedit emulation? {is_editline}")


@unittest.skipUnless(hasattr(readline, "clear_history"),
                     "The history update test cannot be run because the "

            

Reported by Pylint.

Access to a protected member _READLINE_VERSION of a client class
Error

Line: 140 Column: 22

              
class TestReadline(unittest.TestCase):

    @unittest.skipIf(readline._READLINE_VERSION < 0x0601 and not is_editline,
                     "not supported in this library version")
    def test_init(self):
        # Issue #19884: Ensure that the ANSI sequence "\033[1034h" is not
        # written into stdout when the readline module is imported and stdout
        # is redirected to a pipe.

            

Reported by Pylint.

Unused variable 'rc'
Error

Line: 146 Column: 9

                      # Issue #19884: Ensure that the ANSI sequence "\033[1034h" is not
        # written into stdout when the readline module is imported and stdout
        # is redirected to a pipe.
        rc, stdout, stderr = assert_python_ok('-c', 'import readline',
                                              TERM='xterm-256color')
        self.assertEqual(stdout, b'')

    auto_history_script = """\
import readline

            

Reported by Pylint.

Unused variable 'stderr'
Error

Line: 146 Column: 21

                      # Issue #19884: Ensure that the ANSI sequence "\033[1034h" is not
        # written into stdout when the readline module is imported and stdout
        # is redirected to a pipe.
        rc, stdout, stderr = assert_python_ok('-c', 'import readline',
                                              TERM='xterm-256color')
        self.assertEqual(stdout, b'')

    auto_history_script = """\
import readline

            

Reported by Pylint.

Redefining built-in 'input'
Error

Line: 234 Column: 9

              print("history", ascii(readline.get_history_item(1)))
"""

        input = b"\x01"  # Ctrl-A, expands to "|t\xEB[after]"
        input += b"\x02" * len("[after]")  # Move cursor back
        input += b"\t\t"  # Display possible completions
        input += b"x\t"  # Complete "t\xEBx" -> "t\xEBxt"
        input += b"\r"
        output = run_pty(script, input)

            

Reported by Pylint.

Access to a protected member _READLINE_VERSION of a client class
Error

Line: 265 Column: 22

                  #   See https://cnswww.cns.cwru.edu/php/chet/readline/CHANGES
    # - editline: history size is broken on OS X 10.11.6.
    #   Newer versions were not tested yet.
    @unittest.skipIf(readline._READLINE_VERSION < 0x600,
                     "this readline version does not support history-size")
    @unittest.skipIf(is_editline,
                     "editline history size configuration is broken")
    def test_history_size(self):
        history_size = 10

            

Reported by Pylint.

Redefining built-in 'input'
Error

Line: 305 Column: 21

                          self.assertEqual(lines[-1].strip(), b"last input")


def run_pty(script, input=b"dummy input\r", env=None):
    pty = import_module('pty')
    output = bytearray()
    [master, slave] = pty.openpty()
    args = (sys.executable, '-c', script)
    proc = subprocess.Popen(args, stdin=slave, stdout=slave, stderr=slave, env=env)

            

Reported by Pylint.

Lib/test/test_strftime.py
30 issues
Attribute 'gmt' defined outside __init__
Error

Line: 36 Column: 9

              
    def _update_variables(self, now):
        # we must update the local variables on every cycle
        self.gmt = time.gmtime(now)
        now = time.localtime(now)

        if now[3] < 12: self.ampm='(AM|am)'
        else: self.ampm='(PM|pm)'


            

Reported by Pylint.

Attribute 'ampm' defined outside __init__
Error

Line: 39 Column: 25

                      self.gmt = time.gmtime(now)
        now = time.localtime(now)

        if now[3] < 12: self.ampm='(AM|am)'
        else: self.ampm='(PM|pm)'

        self.jan1 = time.localtime(time.mktime((now[0], 1, 1, 0, 0, 0, 0, 1, 0)))

        try:

            

Reported by Pylint.

Attribute 'ampm' defined outside __init__
Error

Line: 40 Column: 15

                      now = time.localtime(now)

        if now[3] < 12: self.ampm='(AM|am)'
        else: self.ampm='(PM|pm)'

        self.jan1 = time.localtime(time.mktime((now[0], 1, 1, 0, 0, 0, 0, 1, 0)))

        try:
            if now[8]: self.tz = time.tzname[1]

            

Reported by Pylint.

Attribute 'jan1' defined outside __init__
Error

Line: 42 Column: 9

                      if now[3] < 12: self.ampm='(AM|am)'
        else: self.ampm='(PM|pm)'

        self.jan1 = time.localtime(time.mktime((now[0], 1, 1, 0, 0, 0, 0, 1, 0)))

        try:
            if now[8]: self.tz = time.tzname[1]
            else: self.tz = time.tzname[0]
        except AttributeError:

            

Reported by Pylint.

Attribute 'tz' defined outside __init__
Error

Line: 45 Column: 24

                      self.jan1 = time.localtime(time.mktime((now[0], 1, 1, 0, 0, 0, 0, 1, 0)))

        try:
            if now[8]: self.tz = time.tzname[1]
            else: self.tz = time.tzname[0]
        except AttributeError:
            self.tz = ''

        if now[3] > 12: self.clock12 = now[3] - 12

            

Reported by Pylint.

Attribute 'tz' defined outside __init__
Error

Line: 46 Column: 19

              
        try:
            if now[8]: self.tz = time.tzname[1]
            else: self.tz = time.tzname[0]
        except AttributeError:
            self.tz = ''

        if now[3] > 12: self.clock12 = now[3] - 12
        elif now[3] > 0: self.clock12 = now[3]

            

Reported by Pylint.

Attribute 'tz' defined outside __init__
Error

Line: 48 Column: 13

                          if now[8]: self.tz = time.tzname[1]
            else: self.tz = time.tzname[0]
        except AttributeError:
            self.tz = ''

        if now[3] > 12: self.clock12 = now[3] - 12
        elif now[3] > 0: self.clock12 = now[3]
        else: self.clock12 = 12


            

Reported by Pylint.

Attribute 'clock12' defined outside __init__
Error

Line: 50 Column: 25

                      except AttributeError:
            self.tz = ''

        if now[3] > 12: self.clock12 = now[3] - 12
        elif now[3] > 0: self.clock12 = now[3]
        else: self.clock12 = 12

        self.now = now


            

Reported by Pylint.

Attribute 'clock12' defined outside __init__
Error

Line: 51 Column: 26

                          self.tz = ''

        if now[3] > 12: self.clock12 = now[3] - 12
        elif now[3] > 0: self.clock12 = now[3]
        else: self.clock12 = 12

        self.now = now

    def setUp(self):

            

Reported by Pylint.

Attribute 'clock12' defined outside __init__
Error

Line: 52 Column: 15

              
        if now[3] > 12: self.clock12 = now[3] - 12
        elif now[3] > 0: self.clock12 = now[3]
        else: self.clock12 = 12

        self.now = now

    def setUp(self):
        try:

            

Reported by Pylint.

PC/getpathp.c
30 issues
wcscpy - Does not check for buffer overflows when copying to destination [MS-banned]
Security

Line: 908 Column: 9 CWE codes: 120
Suggestion: Consider using a function version that stops copying at the end of the buffer

                      }
    }
    if (argv0_path) {
        wcscpy(buf, argv0_path);
        buf = wcschr(buf, L'\0');
        *buf++ = DELIM;
    }
    *(buf - 1) = L'\0';


            

Reported by FlawFinder.

wcscpy - Does not check for buffer overflows when copying to destination [MS-banned]
Security

Line: 1135 Column: 5 CWE codes: 120
Suggestion: Consider using a function version that stops copying at the end of the buffer

              
    /* For back-compat, also search {sys.prefix}\DLLs, though
       that has not been a normal install layout for a while */
    wcscpy(py3path, Py_GetPrefix());
    if (py3path[0]) {
        join(py3path, L"DLLs\\" PY3_DLLNAME);
        hPython3 = LoadLibraryExW(py3path, NULL, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
    }
    return hPython3 != NULL;

            

Reported by FlawFinder.

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

Line: 283 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

              static int
gotlandmark(const wchar_t *prefix, const wchar_t *landmark)
{
    wchar_t filename[MAXPATHLEN+1];
    memset(filename, 0, sizeof(filename));
    wcscpy_s(filename, Py_ARRAY_LENGTH(filename), prefix);
    join(filename, landmark);
    return ismodule(filename, FALSE);
}

            

Reported by FlawFinder.

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

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

                  mbstowcs(keyBufPtr, PyWin_DLLVersionString, versionLen);
    keyBufPtr += versionLen;
    /* NULL comes with this one! */
    memcpy(keyBufPtr, keySuffix, sizeof(keySuffix));
    /* Open the root Python key */
    rc=RegOpenKeyExW(keyBase,
                    keyBuf, /* subkey */
            0, /* reserved */
            KEY_READ,

            

Reported by FlawFinder.

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

Line: 497 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

              {
    PyStatus status;
    const wchar_t *pyvenv_launcher;
    wchar_t program_full_path[MAXPATHLEN+1];
    memset(program_full_path, 0, sizeof(program_full_path));

    if (!GetModuleFileNameW(NULL, program_full_path, MAXPATHLEN)) {
        /* GetModuleFileName should never fail when passed NULL */
        return _PyStatus_ERR("Cannot determine program path");

            

Reported by FlawFinder.

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

Line: 577 Column: 9 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

                  buf[0] = '\0';

    while (!feof(sp_file)) {
        char line[MAXPATHLEN + 1];
        char *p = fgets(line, Py_ARRAY_LENGTH(line), sp_file);
        if (!p) {
            break;
        }
        if (*p == '\0' || *p == '\r' || *p == '\n' || *p == '#') {

            

Reported by FlawFinder.

MultiByteToWideChar - Requires maximum length in CHARACTERS, not bytes
Security

Line: 602 Column: 20 CWE codes: 120

                          goto done;
        }

        DWORD wn = MultiByteToWideChar(CP_UTF8, 0, line, -1, NULL, 0);
        wchar_t *wline = (wchar_t*)PyMem_RawMalloc((wn + 1) * sizeof(wchar_t));
        if (wline == NULL) {
            status = _PyStatus_NO_MEMORY();
            goto done;
        }

            

Reported by FlawFinder.

MultiByteToWideChar - Requires maximum length in CHARACTERS, not bytes
Security

Line: 608 Column: 14 CWE codes: 120

                          status = _PyStatus_NO_MEMORY();
            goto done;
        }
        wn = MultiByteToWideChar(CP_UTF8, 0, line, -1, wline, wn + 1);
        wline[wn] = '\0';

        size_t usedsiz = wcslen(buf);
        while (usedsiz + wn + prefixlen + 4 > bufsiz) {
            bufsiz += MAXPATHLEN;

            

Reported by FlawFinder.

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

Line: 692 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

              calculate_pth_file(PyCalculatePath *calculate, _PyPathConfig *pathconfig,
                   wchar_t *prefix, int *found)
{
    wchar_t filename[MAXPATHLEN+1];

    if (!get_pth_filename(calculate, filename, pathconfig)) {
        return _PyStatus_OK();
    }


            

Reported by FlawFinder.

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

Line: 710 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

              calculate_pyvenv_file(PyCalculatePath *calculate,
                      wchar_t *argv0_path, size_t argv0_path_len)
{
    wchar_t filename[MAXPATHLEN+1];
    const wchar_t *env_cfg = L"pyvenv.cfg";

    /* Filename: <argv0_path_len> / "pyvenv.cfg" */
    wcscpy_s(filename, MAXPATHLEN+1, argv0_path);
    join(filename, env_cfg);

            

Reported by FlawFinder.

Lib/test/time_hashlib.py
30 issues
Unused variable 'f'
Error

Line: 18 Column: 9

              
    localCF = creatorFunc
    start = time.perf_counter()
    for f in range(iterations):
        x = localCF(longStr).digest()
    end = time.perf_counter()

    print(('%2.2f' % (end-start)), "seconds", iterations, "x", len(longStr), "bytes", name)


            

Reported by Pylint.

Unused variable 'x'
Error

Line: 19 Column: 9

                  localCF = creatorFunc
    start = time.perf_counter()
    for f in range(iterations):
        x = localCF(longStr).digest()
    end = time.perf_counter()

    print(('%2.2f' % (end-start)), "seconds", iterations, "x", len(longStr), "bytes", name)

def test_create():

            

Reported by Pylint.

Unused variable 'f'
Error

Line: 26 Column: 9

              
def test_create():
    start = time.perf_counter()
    for f in range(20000):
        d = creatorFunc()
    end = time.perf_counter()

    print(('%2.2f' % (end-start)), "seconds", '[20000 creations]')


            

Reported by Pylint.

Unused variable 'd'
Error

Line: 27 Column: 9

              def test_create():
    start = time.perf_counter()
    for f in range(20000):
        d = creatorFunc()
    end = time.perf_counter()

    print(('%2.2f' % (end-start)), "seconds", '[20000 creations]')

def test_zero():

            

Reported by Pylint.

Unused variable 'f'
Error

Line: 34 Column: 9

              
def test_zero():
    start = time.perf_counter()
    for f in range(20000):
        x = creatorFunc().digest()
    end = time.perf_counter()

    print(('%2.2f' % (end-start)), "seconds", '[20000 "" digests]')


            

Reported by Pylint.

Unused variable 'x'
Error

Line: 35 Column: 9

              def test_zero():
    start = time.perf_counter()
    for f in range(20000):
        x = creatorFunc().digest()
    end = time.perf_counter()

    print(('%2.2f' % (end-start)), "seconds", '[20000 "" digests]')



            

Reported by Pylint.

Use of exec detected.
Security

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

              # setup our creatorFunc to test the requested hash
#
if hName in ('_md5', '_sha'):
    exec('import '+hName)
    exec('creatorFunc = '+hName+'.new')
    print("testing speed of old", hName, "legacy interface")
elif hName == '_hashlib' and len(sys.argv) > 3:
    import _hashlib
    exec('creatorFunc = _hashlib.%s' % sys.argv[2])

            

Reported by Bandit.

Use of exec
Error

Line: 48 Column: 5

              # setup our creatorFunc to test the requested hash
#
if hName in ('_md5', '_sha'):
    exec('import '+hName)
    exec('creatorFunc = '+hName+'.new')
    print("testing speed of old", hName, "legacy interface")
elif hName == '_hashlib' and len(sys.argv) > 3:
    import _hashlib
    exec('creatorFunc = _hashlib.%s' % sys.argv[2])

            

Reported by Pylint.

Use of exec detected.
Security

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

              #
if hName in ('_md5', '_sha'):
    exec('import '+hName)
    exec('creatorFunc = '+hName+'.new')
    print("testing speed of old", hName, "legacy interface")
elif hName == '_hashlib' and len(sys.argv) > 3:
    import _hashlib
    exec('creatorFunc = _hashlib.%s' % sys.argv[2])
    print("testing speed of _hashlib.%s" % sys.argv[2], getattr(_hashlib, sys.argv[2]))

            

Reported by Bandit.

Use of exec
Error

Line: 49 Column: 5

              #
if hName in ('_md5', '_sha'):
    exec('import '+hName)
    exec('creatorFunc = '+hName+'.new')
    print("testing speed of old", hName, "legacy interface")
elif hName == '_hashlib' and len(sys.argv) > 3:
    import _hashlib
    exec('creatorFunc = _hashlib.%s' % sys.argv[2])
    print("testing speed of _hashlib.%s" % sys.argv[2], getattr(_hashlib, sys.argv[2]))

            

Reported by Pylint.