The following issues were found

Lib/unittest/__init__.py
23 issues
Undefined variable name 'IsolatedAsyncioTestCase' in __all__
Error

Line: 47 Column: 38

              SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
"""

__all__ = ['TestResult', 'TestCase', 'IsolatedAsyncioTestCase', 'TestSuite',
           'TextTestRunner', 'TestLoader', 'FunctionTestCase', 'main',
           'defaultTestLoader', 'SkipTest', 'skip', 'skipIf', 'skipUnless',
           'expectedFailure', 'TextTestResult', 'installHandler',
           'registerResult', 'removeResult', 'removeHandler',
           'addModuleCleanup']

            

Reported by Pylint.

Unable to import '__init__.result'
Error

Line: 59 Column: 1

              
__unittest = True

from .result import TestResult
from .case import (addModuleCleanup, TestCase, FunctionTestCase, SkipTest, skip,
                   skipIf, skipUnless, expectedFailure)
from .suite import BaseTestSuite, TestSuite
from .loader import (TestLoader, defaultTestLoader, makeSuite, getTestCaseNames,
                     findTestCases)

            

Reported by Pylint.

Unable to import '__init__.case'
Error

Line: 60 Column: 1

              __unittest = True

from .result import TestResult
from .case import (addModuleCleanup, TestCase, FunctionTestCase, SkipTest, skip,
                   skipIf, skipUnless, expectedFailure)
from .suite import BaseTestSuite, TestSuite
from .loader import (TestLoader, defaultTestLoader, makeSuite, getTestCaseNames,
                     findTestCases)
from .main import TestProgram, main

            

Reported by Pylint.

Unable to import '__init__.suite'
Error

Line: 62 Column: 1

              from .result import TestResult
from .case import (addModuleCleanup, TestCase, FunctionTestCase, SkipTest, skip,
                   skipIf, skipUnless, expectedFailure)
from .suite import BaseTestSuite, TestSuite
from .loader import (TestLoader, defaultTestLoader, makeSuite, getTestCaseNames,
                     findTestCases)
from .main import TestProgram, main
from .runner import TextTestRunner, TextTestResult
from .signals import installHandler, registerResult, removeResult, removeHandler

            

Reported by Pylint.

Unable to import '__init__.loader'
Error

Line: 63 Column: 1

              from .case import (addModuleCleanup, TestCase, FunctionTestCase, SkipTest, skip,
                   skipIf, skipUnless, expectedFailure)
from .suite import BaseTestSuite, TestSuite
from .loader import (TestLoader, defaultTestLoader, makeSuite, getTestCaseNames,
                     findTestCases)
from .main import TestProgram, main
from .runner import TextTestRunner, TextTestResult
from .signals import installHandler, registerResult, removeResult, removeHandler
# IsolatedAsyncioTestCase will be imported lazily.

            

Reported by Pylint.

Unable to import '__init__.main'
Error

Line: 65 Column: 1

              from .suite import BaseTestSuite, TestSuite
from .loader import (TestLoader, defaultTestLoader, makeSuite, getTestCaseNames,
                     findTestCases)
from .main import TestProgram, main
from .runner import TextTestRunner, TextTestResult
from .signals import installHandler, registerResult, removeResult, removeHandler
# IsolatedAsyncioTestCase will be imported lazily.

# deprecated

            

Reported by Pylint.

Unable to import '__init__.runner'
Error

Line: 66 Column: 1

              from .loader import (TestLoader, defaultTestLoader, makeSuite, getTestCaseNames,
                     findTestCases)
from .main import TestProgram, main
from .runner import TextTestRunner, TextTestResult
from .signals import installHandler, registerResult, removeResult, removeHandler
# IsolatedAsyncioTestCase will be imported lazily.

# deprecated
_TextTestResult = TextTestResult

            

Reported by Pylint.

Unable to import '__init__.signals'
Error

Line: 67 Column: 1

                                   findTestCases)
from .main import TestProgram, main
from .runner import TextTestRunner, TextTestResult
from .signals import installHandler, registerResult, removeResult, removeHandler
# IsolatedAsyncioTestCase will be imported lazily.

# deprecated
_TextTestResult = TextTestResult


            

Reported by Pylint.

Unable to import '__init__.async_case'
Error

Line: 93 Column: 9

              def __getattr__(name):
    if name == 'IsolatedAsyncioTestCase':
        global IsolatedAsyncioTestCase
        from .async_case import IsolatedAsyncioTestCase
        return IsolatedAsyncioTestCase
    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")

            

Reported by Pylint.

Unused argument 'tests'
Error

Line: 76 Column: 24

              # There are no tests here, so don't try to run anything discovered from
# introspecting the symbols (e.g. FunctionTestCase). Instead, all our
# tests come from within unittest.test.
def load_tests(loader, tests, pattern):
    import os.path
    # top level directory cached on loader instance
    this_dir = os.path.dirname(__file__)
    return loader.discover(start_dir=this_dir, pattern=pattern)


            

Reported by Pylint.

Tools/scripts/finddiv.py
23 issues
Unused variable 'a'
Error

Line: 33 Column: 12

                      usage("at least one file argument is required")
        return 2
    listnames = 0
    for o, a in opts:
        if o == "-h":
            print(__doc__)
            return
        if o == "-l":
            listnames = 1

            

Reported by Pylint.

Redefining built-in 'exit'
Error

Line: 39 Column: 5

                          return
        if o == "-l":
            listnames = 1
    exit = None
    for filename in args:
        x = process(filename, listnames)
        exit = exit or x
    return exit


            

Reported by Pylint.

Unused variable 'type'
Error

Line: 61 Column: 13

                  with fp:
        g = tokenize.generate_tokens(fp.readline)
        lastrow = None
        for type, token, (row, col), end, line in g:
            if token in ("/", "/="):
                if listnames:
                    print(filename)
                    break
                if row != lastrow:

            

Reported by Pylint.

Redefining built-in 'type'
Error

Line: 61 Column: 13

                  with fp:
        g = tokenize.generate_tokens(fp.readline)
        lastrow = None
        for type, token, (row, col), end, line in g:
            if token in ("/", "/="):
                if listnames:
                    print(filename)
                    break
                if row != lastrow:

            

Reported by Pylint.

Unused variable 'end'
Error

Line: 61 Column: 38

                  with fp:
        g = tokenize.generate_tokens(fp.readline)
        lastrow = None
        for type, token, (row, col), end, line in g:
            if token in ("/", "/="):
                if listnames:
                    print(filename)
                    break
                if row != lastrow:

            

Reported by Pylint.

Unused variable 'col'
Error

Line: 61 Column: 32

                  with fp:
        g = tokenize.generate_tokens(fp.readline)
        lastrow = None
        for type, token, (row, col), end, line in g:
            if token in ("/", "/="):
                if listnames:
                    print(filename)
                    break
                if row != lastrow:

            

Reported by Pylint.

Redefining built-in 'dir'
Error

Line: 70 Column: 16

                                  lastrow = row
                    print("%s:%d:%s" % (filename, row, line), end=' ')

def processdir(dir, listnames):
    try:
        names = os.listdir(dir)
    except OSError as msg:
        sys.stderr.write("Can't list directory: %s\n" % dir)
        return 1

            

Reported by Pylint.

Unused variable 'msg'
Error

Line: 73 Column: 5

              def processdir(dir, listnames):
    try:
        names = os.listdir(dir)
    except OSError as msg:
        sys.stderr.write("Can't list directory: %s\n" % dir)
        return 1
    files = []
    for name in names:
        fn = os.path.join(dir, name)

            

Reported by Pylint.

Redefining built-in 'exit'
Error

Line: 82 Column: 5

                      if os.path.normcase(fn).endswith(".py") or os.path.isdir(fn):
            files.append(fn)
    files.sort(key=os.path.normcase)
    exit = None
    for fn in files:
        x = process(fn, listnames)
        exit = exit or x
    return exit


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 23 Column: 1

              import getopt
import tokenize

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "lh")
    except getopt.error as msg:
        usage(msg)
        return 2

            

Reported by Pylint.

Tools/scripts/pdeps.py
23 issues
Redefining built-in 'list'
Error

Line: 71 Column: 22

                      mod = os.path.basename(filename)
        if mod[-3:] == '.py':
            mod = mod[:-3]
        table[mod] = list = []
        while 1:
            line = fp.readline()
            if not line: break
            while line[-1:] == '\\':
                nextline = fp.readline()

            

Reported by Pylint.

Unused variable 'b'
Error

Line: 81 Column: 21

                              line = line[:-1] + nextline
            m_found = m_import.match(line) or m_from.match(line)
            if m_found:
                (a, b), (a1, b1) = m_found.regs[:2]
            else: continue
            words = line[a1:b1].split(',')
            # print '#', line, words
            for word in words:
                word = word.strip()

            

Reported by Pylint.

Unused variable 'a'
Error

Line: 81 Column: 18

                              line = line[:-1] + nextline
            m_found = m_import.match(line) or m_from.match(line)
            if m_found:
                (a, b), (a1, b1) = m_found.regs[:2]
            else: continue
            words = line[a1:b1].split(',')
            # print '#', line, words
            for word in words:
                word = word.strip()

            

Reported by Pylint.

Redefining built-in 'dict'
Error

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

                  maxlen = 0
    for mod in modules: maxlen = max(maxlen, len(mod))
    for mod in modules:
        list = sorted(table[mod])
        print(mod.ljust(maxlen), ':', end=' ')
        if mod in list:
            print('(*)', end=' ')
        for ref in list:
            print(ref, end=' ')

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              #! /usr/bin/env python3

# pdeps
#
# Find dependencies between a bunch of Python modules.
#
# Usage:
#       pdeps file1.py file2.py ...
#

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 30 Column: 1

              
# Main program
#
def main():
    args = sys.argv[1:]
    if not args:
        print('usage: pdeps file.py file.py ...')
        return 2
    #

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 66 Column: 1

              
# Collect data from one file
#
def process(filename, table):
    with open(filename, encoding='utf-8') as fp:
        mod = os.path.basename(filename)
        if mod[-3:] == '.py':
            mod = mod[:-3]
        table[mod] = list = []

            

Reported by Pylint.

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

Line: 67 Column: 46

              # Collect data from one file
#
def process(filename, table):
    with open(filename, encoding='utf-8') as fp:
        mod = os.path.basename(filename)
        if mod[-3:] == '.py':
            mod = mod[:-3]
        table[mod] = list = []
        while 1:

            

Reported by Pylint.

More than one statement on a single line
Error

Line: 74 Column: 26

                      table[mod] = list = []
        while 1:
            line = fp.readline()
            if not line: break
            while line[-1:] == '\\':
                nextline = fp.readline()
                if not nextline: break
                line = line[:-1] + nextline
            m_found = m_import.match(line) or m_from.match(line)

            

Reported by Pylint.

Tools/pynche/Switchboard.py
23 issues
Deserialization with the marshal module is possibly dangerous.
Security blacklist

Line: 65
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b302-marshal

                          try:
                try:
                    fp = open(initfile, 'rb')
                    self.__optiondb = marshal.load(fp)
                    if not isinstance(self.__optiondb, dict):
                        print('Problem reading options from file:', initfile,
                              file=sys.stderr)
                        self.__optiondb = {}
                except (IOError, EOFError, ValueError):

            

Reported by Bandit.

Module name "Switchboard" doesn't conform to snake_case naming style
Error

Line: 1 Column: 1

              """Switchboard class.

This class is used to coordinate updates among all Viewers.  Every Viewer must
conform to the following interface:

    - it must include a method called update_yourself() which takes three
      arguments; the red, green, and blue values of the selected color.

    - When a Viewer selects a color and wishes to update all other Views, it

            

Reported by Pylint.

Missing class docstring
Error

Line: 49 Column: 1

              


class Switchboard:
    def __init__(self, initfile):
        self.__initfile = initfile
        self.__colordb = None
        self.__optiondb = {}
        self.__views = []

            

Reported by Pylint.

Too many instance attributes (8/7)
Error

Line: 49 Column: 1

              


class Switchboard:
    def __init__(self, initfile):
        self.__initfile = initfile
        self.__colordb = None
        self.__optiondb = {}
        self.__views = []

            

Reported by Pylint.

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

Line: 60 Column: 9

                      self.__blue = 0
        self.__canceled = 0
        # read the initialization file
        fp = None
        if initfile:
            try:
                try:
                    fp = open(initfile, 'rb')
                    self.__optiondb = marshal.load(fp)

            

Reported by Pylint.

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

Line: 64 Column: 21

                      if initfile:
            try:
                try:
                    fp = open(initfile, 'rb')
                    self.__optiondb = marshal.load(fp)
                    if not isinstance(self.__optiondb, dict):
                        print('Problem reading options from file:', initfile,
                              file=sys.stderr)
                        self.__optiondb = {}

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 76 Column: 5

                              if fp:
                    fp.close()

    def add_view(self, view):
        self.__views.append(view)

    def update_views(self, red, green, blue):
        self.__red = red
        self.__green = green

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 79 Column: 5

                  def add_view(self, view):
        self.__views.append(view)

    def update_views(self, red, green, blue):
        self.__red = red
        self.__green = green
        self.__blue = blue
        for v in self.__views:
            v.update_yourself(red, green, blue)

            

Reported by Pylint.

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

Line: 83 Column: 13

                      self.__red = red
        self.__green = green
        self.__blue = blue
        for v in self.__views:
            v.update_yourself(red, green, blue)

    def update_views_current(self):
        self.update_views(self.__red, self.__green, self.__blue)


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 86 Column: 5

                      for v in self.__views:
            v.update_yourself(red, green, blue)

    def update_views_current(self):
        self.update_views(self.__red, self.__green, self.__blue)

    def current_rgb(self):
        return self.__red, self.__green, self.__blue


            

Reported by Pylint.

Tools/scripts/abitype.py
22 issues
Redefining name 'v' from outer scope (line 201)
Error

Line: 16 Column: 11

              # =, {, }, ; : themselves
def classify():
    res = []
    for t,v in tokens:
        if t == 'other' and v in "={};":
            res.append(v)
        elif t == 'ident':
            if v == 'PyTypeObject':
                res.append('T')

            

Reported by Pylint.

Redefining name 't' from outer scope (line 201)
Error

Line: 16 Column: 9

              # =, {, }, ; : themselves
def classify():
    res = []
    for t,v in tokens:
        if t == 'other' and v in "={};":
            res.append(v)
        elif t == 'ident':
            if v == 'PyTypeObject':
                res.append('T')

            

Reported by Pylint.

Redefining name 'start' from outer scope (line 195)
Error

Line: 37 Column: 16

              # All comments are dropped from the variable (which are typically
# just the slot names, anyway), and information is discarded whether
# the original type was static.
def get_fields(start, real_end):
    pos = start
    # static?
    if tokens[pos][1] == 'static':
        pos += 2
    # PyTypeObject

            

Reported by Pylint.

Redefining name 'pos' from outer scope (line 171)
Error

Line: 38 Column: 5

              # just the slot names, anyway), and information is discarded whether
# the original type was static.
def get_fields(start, real_end):
    pos = start
    # static?
    if tokens[pos][1] == 'static':
        pos += 2
    # PyTypeObject
    pos += 2

            

Reported by Pylint.

Redefining name 'name' from outer scope (line 197)
Error

Line: 45 Column: 5

                  # PyTypeObject
    pos += 2
    # name
    name = tokens[pos][1]
    pos += 1
    while tokens[pos][1] != '{':
        pos += 1
    pos += 1
    # PyVarObject_HEAD_INIT

            

Reported by Pylint.

Redefining name 'fields' from outer scope (line 197)
Error

Line: 59 Column: 5

                      pos += 1
    pos += 1
    # field definitions: various tokens, comma-separated
    fields = []
    while True:
        while tokens[pos][0] in ('ws', 'comment'):
            pos += 1
        end = pos
        while tokens[end][1] not in ',}':

            

Reported by Pylint.

Redefining name 'end' from outer scope (line 196)
Error

Line: 63 Column: 9

                  while True:
        while tokens[pos][0] in ('ws', 'comment'):
            pos += 1
        end = pos
        while tokens[end][1] not in ',}':
            if tokens[end][1] == '(':
                nesting = 1
                while nesting:
                    end += 1

            

Reported by Pylint.

Redefining name 'name' from outer scope (line 197)
Error

Line: 134 Column: 16

              ]

# Generate a PyType_Spec definition
def make_slots(name, fields):
    res = []
    res.append('static PyType_Slot %s_slots[] = {' % name)
    # defaults for spec
    spec = { 'tp_itemsize':'0' }
    for i, val in enumerate(fields):

            

Reported by Pylint.

Redefining name 'fields' from outer scope (line 197)
Error

Line: 134 Column: 22

              ]

# Generate a PyType_Spec definition
def make_slots(name, fields):
    res = []
    res.append('static PyType_Slot %s_slots[] = {' % name)
    # defaults for spec
    spec = { 'tp_itemsize':'0' }
    for i, val in enumerate(fields):

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              #!/usr/bin/env python3
# This script converts a C file to use the PEP 384 type definition API
# Usage: abitype.py < old_code > new_code
import re, sys

###### Replacement of PyTypeObject static instances ##############

# classify each token, giving it a one-letter code:
# S: static

            

Reported by Pylint.

Lib/py_compile.py
22 issues
Cannot import 'traceback' due to syntax error 'invalid syntax (<unknown>, line 576)'
Error

Line: 13 Column: 1

              import os
import os.path
import sys
import traceback

__all__ = ["compile", "main", "PyCompileError", "PycInvalidationMode"]


class PyCompileError(Exception):

            

Reported by Pylint.

Redefining built-in 'compile'
Error

Line: 79 Column: 1

                      return PycInvalidationMode.TIMESTAMP


def compile(file, cfile=None, dfile=None, doraise=False, optimize=-1,
            invalidation_mode=None, quiet=0):
    """Byte-compile one Python source file to Python bytecode.

    :param file: The source file name.
    :param cfile: The target byte compiled file name.  When not given, this

            

Reported by Pylint.

Catching too general exception Exception
Error

Line: 146 Column: 12

                  try:
        code = loader.source_to_code(source_bytes, dfile or file,
                                     _optimize=optimize)
    except Exception as err:
        py_exc = PyCompileError(err.__class__, err, dfile or file)
        if quiet < 2:
            if doraise:
                raise py_exc
            else:

            

Reported by Pylint.

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

Line: 150 Column: 17

                      py_exc = PyCompileError(err.__class__, err, dfile or file)
        if quiet < 2:
            if doraise:
                raise py_exc
            else:
                sys.stderr.write(py_exc.msg + '\n')
        return
    try:
        dirname = os.path.dirname(cfile)

            

Reported by Pylint.

Access to a protected member _bootstrap_external of a client class
Error

Line: 162 Column: 20

                      pass
    if invalidation_mode == PycInvalidationMode.TIMESTAMP:
        source_stats = loader.path_stats(file)
        bytecode = importlib._bootstrap_external._code_to_timestamp_pyc(
            code, source_stats['mtime'], source_stats['size'])
    else:
        source_hash = importlib.util.source_hash(source_bytes)
        bytecode = importlib._bootstrap_external._code_to_hash_pyc(
            code,

            

Reported by Pylint.

Access to a protected member _code_to_timestamp_pyc of a client class
Error

Line: 162 Column: 20

                      pass
    if invalidation_mode == PycInvalidationMode.TIMESTAMP:
        source_stats = loader.path_stats(file)
        bytecode = importlib._bootstrap_external._code_to_timestamp_pyc(
            code, source_stats['mtime'], source_stats['size'])
    else:
        source_hash = importlib.util.source_hash(source_bytes)
        bytecode = importlib._bootstrap_external._code_to_hash_pyc(
            code,

            

Reported by Pylint.

Access to a protected member _bootstrap_external of a client class
Error

Line: 166 Column: 20

                          code, source_stats['mtime'], source_stats['size'])
    else:
        source_hash = importlib.util.source_hash(source_bytes)
        bytecode = importlib._bootstrap_external._code_to_hash_pyc(
            code,
            source_hash,
            (invalidation_mode == PycInvalidationMode.CHECKED_HASH),
        )
    mode = importlib._bootstrap_external._calc_mode(file)

            

Reported by Pylint.

Access to a protected member _code_to_hash_pyc of a client class
Error

Line: 166 Column: 20

                          code, source_stats['mtime'], source_stats['size'])
    else:
        source_hash = importlib.util.source_hash(source_bytes)
        bytecode = importlib._bootstrap_external._code_to_hash_pyc(
            code,
            source_hash,
            (invalidation_mode == PycInvalidationMode.CHECKED_HASH),
        )
    mode = importlib._bootstrap_external._calc_mode(file)

            

Reported by Pylint.

Access to a protected member _calc_mode of a client class
Error

Line: 171 Column: 12

                          source_hash,
            (invalidation_mode == PycInvalidationMode.CHECKED_HASH),
        )
    mode = importlib._bootstrap_external._calc_mode(file)
    importlib._bootstrap_external._write_atomic(cfile, bytecode, mode)
    return cfile


def main():

            

Reported by Pylint.

Access to a protected member _bootstrap_external of a client class
Error

Line: 171 Column: 12

                          source_hash,
            (invalidation_mode == PycInvalidationMode.CHECKED_HASH),
        )
    mode = importlib._bootstrap_external._calc_mode(file)
    importlib._bootstrap_external._write_atomic(cfile, bytecode, mode)
    return cfile


def main():

            

Reported by Pylint.

Lib/test/test_asyncio/test_server.py
22 issues
Instance of 'BaseStartServer' has no 'assertFalse' member
Error

Line: 51 Column: 9

                      srv = self.loop.run_until_complete(asyncio.start_server(
            serve, socket_helper.HOSTv4, 0, start_serving=False))

        self.assertFalse(srv.is_serving())

        main_task = self.loop.create_task(main(srv))

        addr = srv.sockets[0].getsockname()
        with self.assertRaises(asyncio.CancelledError):

            

Reported by Pylint.

Instance of 'BaseStartServer' has no 'assertRaises' member
Error

Line: 56 Column: 14

                      main_task = self.loop.create_task(main(srv))

        addr = srv.sockets[0].getsockname()
        with self.assertRaises(asyncio.CancelledError):
            with self.tcp_client(lambda sock: client(sock, addr)):
                self.loop.run_until_complete(main_task)

        self.assertEqual(srv.sockets, ())


            

Reported by Pylint.

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

Line: 60 Column: 9

                          with self.tcp_client(lambda sock: client(sock, addr)):
                self.loop.run_until_complete(main_task)

        self.assertEqual(srv.sockets, ())

        self.assertIsNone(srv._sockets)
        self.assertIsNone(srv._waiters)
        self.assertFalse(srv.is_serving())


            

Reported by Pylint.

Instance of 'BaseStartServer' has no 'assertIsNone' member
Error

Line: 62 Column: 9

              
        self.assertEqual(srv.sockets, ())

        self.assertIsNone(srv._sockets)
        self.assertIsNone(srv._waiters)
        self.assertFalse(srv.is_serving())

        with self.assertRaisesRegex(RuntimeError, r'is closed'):
            self.loop.run_until_complete(srv.serve_forever())

            

Reported by Pylint.

Instance of 'BaseStartServer' has no 'assertIsNone' member
Error

Line: 63 Column: 9

                      self.assertEqual(srv.sockets, ())

        self.assertIsNone(srv._sockets)
        self.assertIsNone(srv._waiters)
        self.assertFalse(srv.is_serving())

        with self.assertRaisesRegex(RuntimeError, r'is closed'):
            self.loop.run_until_complete(srv.serve_forever())


            

Reported by Pylint.

Instance of 'BaseStartServer' has no 'assertFalse' member
Error

Line: 64 Column: 9

              
        self.assertIsNone(srv._sockets)
        self.assertIsNone(srv._waiters)
        self.assertFalse(srv.is_serving())

        with self.assertRaisesRegex(RuntimeError, r'is closed'):
            self.loop.run_until_complete(srv.serve_forever())



            

Reported by Pylint.

Instance of 'BaseStartServer' has no 'assertRaisesRegex' member
Error

Line: 66 Column: 14

                      self.assertIsNone(srv._waiters)
        self.assertFalse(srv.is_serving())

        with self.assertRaisesRegex(RuntimeError, r'is closed'):
            self.loop.run_until_complete(srv.serve_forever())


class SelectorStartServerTests(BaseStartServer, unittest.TestCase):


            

Reported by Pylint.

Unused variable 'i'
Error

Line: 24 Column: 17

                      HELLO_MSG = b'1' * 1024 * 5 + b'\n'

        def client(sock, addr):
            for i in range(10):
                time.sleep(0.2)
                if srv.is_serving():
                    break
            else:
                raise RuntimeError

            

Reported by Pylint.

Access to a protected member _sockets of a client class
Error

Line: 62 Column: 27

              
        self.assertEqual(srv.sockets, ())

        self.assertIsNone(srv._sockets)
        self.assertIsNone(srv._waiters)
        self.assertFalse(srv.is_serving())

        with self.assertRaisesRegex(RuntimeError, r'is closed'):
            self.loop.run_until_complete(srv.serve_forever())

            

Reported by Pylint.

Access to a protected member _waiters of a client class
Error

Line: 63 Column: 27

                      self.assertEqual(srv.sockets, ())

        self.assertIsNone(srv._sockets)
        self.assertIsNone(srv._waiters)
        self.assertFalse(srv.is_serving())

        with self.assertRaisesRegex(RuntimeError, r'is closed'):
            self.loop.run_until_complete(srv.serve_forever())


            

Reported by Pylint.

Lib/test/test_mailcap.py
22 issues
Missing module docstring
Error

Line: 1 Column: 1

              import mailcap
import os
import copy
import test.support
from test.support import os_helper
import unittest
import sys

# Location of mailcap file

            

Reported by Pylint.

Line too long (102/100)
Error

Line: 42 Column: 1

                      [{'composetyped': 'extcompose %s',
          'description': '"A reference to data stored in an external location"',
          'needsterminal': '',
          'view': 'showexternal %s %{access-type} %{name} %{site}     %{directory} %{mode} %{server}',
          'lineno': 10}],
    'text/richtext':
        [{'test': 'test "`echo     %{charset} | tr \'[A-Z]\' \'[a-z]\'`"  = iso-8859-8',
          'copiousoutput': '',
          'view': 'shownonascii iso-8859-8 -e richtext -p %s',

            

Reported by Pylint.

Missing class docstring
Error

Line: 69 Column: 1

                      entry.pop('lineno')


class HelperFunctionTest(unittest.TestCase):

    def test_listmailcapfiles(self):
        # The return value for listmailcapfiles() will vary by system.
        # So verify that listmailcapfiles() returns a list of strings that is of
        # non-zero length.

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 71 Column: 5

              
class HelperFunctionTest(unittest.TestCase):

    def test_listmailcapfiles(self):
        # The return value for listmailcapfiles() will vary by system.
        # So verify that listmailcapfiles() returns a list of strings that is of
        # non-zero length.
        mcfiles = mailcap.listmailcapfiles()
        self.assertIsInstance(mcfiles, list)

            

Reported by Pylint.

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

Line: 77 Column: 13

                      # non-zero length.
        mcfiles = mailcap.listmailcapfiles()
        self.assertIsInstance(mcfiles, list)
        for m in mcfiles:
            self.assertIsInstance(m, str)
        with os_helper.EnvironmentVarGuard() as env:
            # According to RFC 1524, if MAILCAPS env variable exists, use that
            # and only that.
            if "MAILCAPS" in env:

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 90 Column: 5

                              mcfiles = mailcap.listmailcapfiles()
        self.assertEqual(env_mailcaps, mcfiles)

    def test_readmailcapfile(self):
        # Test readmailcapfile() using test file. It should match MAILCAPDICT.
        with open(MAILCAPFILE, 'r') as mcf:
            with self.assertWarns(DeprecationWarning):
                d = mailcap.readmailcapfile(mcf)
        self.assertDictEqual(d, MAILCAPDICT_DEPRECATED)

            

Reported by Pylint.

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

Line: 94 Column: 17

                      # Test readmailcapfile() using test file. It should match MAILCAPDICT.
        with open(MAILCAPFILE, 'r') as mcf:
            with self.assertWarns(DeprecationWarning):
                d = mailcap.readmailcapfile(mcf)
        self.assertDictEqual(d, MAILCAPDICT_DEPRECATED)

    def test_lookup(self):
        # Test without key
        expected = [{'view': 'animate %s', 'lineno': 12},

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 97 Column: 5

                              d = mailcap.readmailcapfile(mcf)
        self.assertDictEqual(d, MAILCAPDICT_DEPRECATED)

    def test_lookup(self):
        # Test without key
        expected = [{'view': 'animate %s', 'lineno': 12},
                    {'view': 'mpeg_play %s', 'lineno': 13}]
        actual = mailcap.lookup(MAILCAPDICT, 'video/mpeg')
        self.assertListEqual(expected, actual)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 119 Column: 5

                      actual = mailcap.lookup(MAILCAPDICT_DEPRECATED, 'video/mpeg')
        self.assertListEqual(expected, actual)

    def test_subst(self):
        plist = ['id=1', 'number=2', 'total=3']
        # test case: ([field, MIMEtype, filename, plist=[]], <expected string>)
        test_cases = [
            (["", "audio/*", "foo.txt"], ""),
            (["echo foo", "audio/*", "foo.txt"], "echo foo"),

            

Reported by Pylint.

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

Line: 131 Column: 13

                          (["echo foo", "audio/*", "foo.txt", plist], "echo foo"),
            (["echo %{total}", "audio/*", "foo.txt", plist], "echo 3")
        ]
        for tc in test_cases:
            self.assertEqual(mailcap.subst(*tc[0]), tc[1])


class GetcapsTest(unittest.TestCase):


            

Reported by Pylint.

Lib/test/bisect_cmd.py
22 issues
Access to a protected member _args_from_interpreter_flags of a client class
Error

Line: 52 Column: 16

              
def python_cmd():
    cmd = [sys.executable]
    cmd.extend(subprocess._args_from_interpreter_flags())
    cmd.extend(subprocess._optim_args_from_interpreter_flags())
    return cmd


def list_cases(args):

            

Reported by Pylint.

Access to a protected member _optim_args_from_interpreter_flags of a client class
Error

Line: 53 Column: 16

              def python_cmd():
    cmd = [sys.executable]
    cmd.extend(subprocess._args_from_interpreter_flags())
    cmd.extend(subprocess._optim_args_from_interpreter_flags())
    return cmd


def list_cases(args):
    cmd = python_cmd()

            

Reported by Pylint.

Using subprocess.run without explicitly set `check` is not recommended.
Error

Line: 61 Column: 12

                  cmd = python_cmd()
    cmd.extend(['-m', 'test', '--list-cases'])
    cmd.extend(args.test_args)
    proc = subprocess.run(cmd,
                          stdout=subprocess.PIPE,
                          universal_newlines=True)
    exitcode = proc.returncode
    if exitcode:
        cmd = format_shell_args(cmd)

            

Reported by Pylint.

Unused argument 'huntrleaks'
Error

Line: 74 Column: 28

                  return tests


def run_tests(args, tests, huntrleaks=None):
    tmp = tempfile.mktemp()
    try:
        write_tests(tmp, tests)

        cmd = python_cmd()

            

Reported by Pylint.

Use of insecure and deprecated function (mktemp).
Security blacklist

Line: 75
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b306-mktemp-q

              

def run_tests(args, tests, huntrleaks=None):
    tmp = tempfile.mktemp()
    try:
        write_tests(tmp, tests)

        cmd = python_cmd()
        cmd.extend(['-m', 'test', '--matchfile', tmp])

            

Reported by Bandit.

Using subprocess.run without explicitly set `check` is not recommended.
Error

Line: 83 Column: 16

                      cmd.extend(['-m', 'test', '--matchfile', tmp])
        cmd.extend(args.test_args)
        print("+ %s" % format_shell_args(cmd))
        proc = subprocess.run(cmd)
        return proc.returncode
    finally:
        if os.path.exists(tmp):
            os.unlink(tmp)


            

Reported by Pylint.

FIXME: document that following arguments are test arguments
Error

Line: 103 Column: 3

                  parser.add_argument('-N', '--max-iter', type=int, default=100,
                        help='Maximum number of bisection iterations '
                             '(default: 100)')
    # FIXME: document that following arguments are test arguments

    args, test_args = parser.parse_known_args()
    args.test_args = test_args
    return args


            

Reported by Pylint.

Consider possible security implications associated with subprocess module.
Security blacklist

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

              import os.path
import math
import random
import subprocess
import sys
import tempfile
import time



            

Reported by Bandit.

Missing function or method docstring
Error

Line: 31 Column: 1

              import time


def write_tests(filename, tests):
    with open(filename, "w") as fp:
        for name in tests:
            print(name, file=fp)
        fp.flush()


            

Reported by Pylint.

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

Line: 32 Column: 33

              

def write_tests(filename, tests):
    with open(filename, "w") as fp:
        for name in tests:
            print(name, file=fp)
        fp.flush()



            

Reported by Pylint.

Lib/multiprocessing/shared_memory.py
22 issues
Unable to import '_winapi'
Error

Line: 20 Column: 5

              import types

if os.name == "nt":
    import _winapi
    _USE_POSIX = False
else:
    import _posixshmem
    _USE_POSIX = True


            

Reported by Pylint.

Attempted relative import beyond top-level package
Error

Line: 119 Column: 13

                              self.unlink()
                raise

            from .resource_tracker import register
            register(self._name, "shared_memory")

        else:

            # Windows Named Shared Memory

            

Reported by Pylint.

Attempted relative import beyond top-level package
Error

Line: 240 Column: 13

                      called once (and only once) across all processes which have access
        to the shared memory block."""
        if _USE_POSIX and self._name:
            from .resource_tracker import unregister
            _posixshmem.shm_unlink(self._name)
            unregister(self._name, "shared_memory")


_encoding = "utf8"

            

Reported by Pylint.

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

Line: 432 Column: 13

                              offset
            )
        except IndexError:
            raise IndexError("index out of range")

        back_transform = self._get_back_transform(position)
        v = back_transform(v)

        return v

            

Reported by Pylint.

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

Line: 446 Column: 13

                          offset = self._offset_data_start + item_offset
            current_format = self._get_packing_format(position)
        except IndexError:
            raise IndexError("assignment index out of range")

        if not isinstance(value, (str, bytes)):
            new_format = self._types_mapping[type(value)]
            encoded_value = value
        else:

            

Reported by Pylint.

Else clause on loop without a break statement
Error

Line: 529 Column: 9

                      for position, entry in enumerate(self):
            if value == entry:
                return position
        else:
            raise ValueError(f"{value!r} not in this container")

    __class_getitem__ = classmethod(types.GenericAlias)

            

Reported by Pylint.

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

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

                  "Create a random filename for the shared memory object."
    # number of random bytes to use for name
    nbytes = (_SHM_SAFE_NAME_LENGTH - len(_SHM_NAME_PREFIX)) // 2
    assert nbytes >= 2, '_SHM_NAME_PREFIX too long'
    name = _SHM_NAME_PREFIX + secrets.token_hex(nbytes)
    assert len(name) <= _SHM_SAFE_NAME_LENGTH
    return name



            

Reported by Bandit.

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

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

                  nbytes = (_SHM_SAFE_NAME_LENGTH - len(_SHM_NAME_PREFIX)) // 2
    assert nbytes >= 2, '_SHM_NAME_PREFIX too long'
    name = _SHM_NAME_PREFIX + secrets.token_hex(nbytes)
    assert len(name) <= _SHM_SAFE_NAME_LENGTH
    return name


class SharedMemory:
    """Creates a new shared memory block or attaches to an existing

            

Reported by Bandit.

The if expression can be replaced with 'bool(test)'
Error

Line: 72 Column: 30

                  _buf = None
    _flags = os.O_RDWR
    _mode = 0o600
    _prepend_leading_slash = True if _USE_POSIX else False

    def __init__(self, name=None, create=False, size=0):
        if not size >= 0:
            raise ValueError("'size' must be a positive integer")
        if create:

            

Reported by Pylint.

Too many branches (21/12)
Error

Line: 74 Column: 5

                  _mode = 0o600
    _prepend_leading_slash = True if _USE_POSIX else False

    def __init__(self, name=None, create=False, size=0):
        if not size >= 0:
            raise ValueError("'size' must be a positive integer")
        if create:
            self._flags = _O_CREX | os.O_RDWR
            if size == 0:

            

Reported by Pylint.