The following issues were found

Lib/test/inspect_fodder2.py
210 issues
Undefined variable 'world'
Error

Line: 59 Column: 5

              
# line 57
def with_comment():  # hello
    world

# line 61
multiline_sig = [
    lambda x, \
            y: x+y,

            

Reported by Pylint.

Method has no argument
Error

Line: 71 Column: 9

              # line 68
def func69():
    class cls70:
        def func71():
            pass
    return cls70
extra74 = 74

# line 76

            

Reported by Pylint.

Method has no argument
Error

Line: 83 Column: 5

              
# line 81
class cls82:
    def func83(): pass
(extra84, stuff84) = 'xy'
extra85 = 'stop'

# line 87
def func88():

            

Reported by Pylint.

Method has no argument
Error

Line: 95 Column: 9

              # line 92
def f():
    class X:
        def g():
            "doc"
            return 42
    return X
method_in_dynamic_class = f().g


            

Reported by Pylint.

Method has no argument
Error

Line: 136 Column: 5

              
#line 134
class cls135:
    def func136():
        def func137():
            never_reached1
            never_reached2

# line 141

            

Reported by Pylint.

Undefined variable 'never_reached1'
Error

Line: 138 Column: 13

              class cls135:
    def func136():
        def func137():
            never_reached1
            never_reached2

# line 141
class cls142:
    a = """

            

Reported by Pylint.

Undefined variable 'never_reached2'
Error

Line: 139 Column: 13

                  def func136():
        def func137():
            never_reached1
            never_reached2

# line 141
class cls142:
    a = """
class cls149:

            

Reported by Pylint.

Unused argument 'foo'
Error

Line: 2 Column: 10

              # line 1
def wrap(foo=None):
    def wrapper(func):
        return func
    return wrapper

# line 7
def replace(func):
    def insteadfunc():

            

Reported by Pylint.

Unused argument 'func'
Error

Line: 8 Column: 13

                  return wrapper

# line 7
def replace(func):
    def insteadfunc():
        print('hello')
    return insteadfunc

# line 13

            

Reported by Pylint.

Unused argument 'arg1'
Error

Line: 40 Column: 14

              def onelinefunc(): pass

# line 39
def manyargs(arg1, arg2,
arg3, arg4): pass

# line 43
def twolinefunc(m): return m and \
m

            

Reported by Pylint.

Lib/test/lock_tests.py
209 issues
Generator 'generator' has no '__enter__' member
Error

Line: 42 Column: 9

                      self.finished = []
        self._can_exit = not wait_before_exit
        self.wait_thread = threading_helper.wait_threads_exit()
        self.wait_thread.__enter__()

        def task():
            tid = threading.get_ident()
            self.started.append(tid)
            try:

            

Reported by Pylint.

Generator 'generator' has no '__exit__' member
Error

Line: 69 Column: 9

                      while len(self.finished) < self.n:
            _wait()
        # Wait for threads exit
        self.wait_thread.__exit__(None, None, None)

    def do_finish(self):
        self._can_exit = True



            

Reported by Pylint.

Instance of 'BaseLockTests' has no 'locktype' member
Error

Line: 98 Column: 16

                  """

    def test_constructor(self):
        lock = self.locktype()
        del lock

    def test_repr(self):
        lock = self.locktype()
        self.assertRegex(repr(lock), "<unlocked .* object (.*)?at .*>")

            

Reported by Pylint.

Instance of 'BaseLockTests' has no 'locktype' member
Error

Line: 102 Column: 16

                      del lock

    def test_repr(self):
        lock = self.locktype()
        self.assertRegex(repr(lock), "<unlocked .* object (.*)?at .*>")
        del lock

    def test_locked_repr(self):
        lock = self.locktype()

            

Reported by Pylint.

Instance of 'BaseLockTests' has no 'locktype' member
Error

Line: 107 Column: 16

                      del lock

    def test_locked_repr(self):
        lock = self.locktype()
        lock.acquire()
        self.assertRegex(repr(lock), "<locked .* object (.*)?at .*>")
        del lock

    def test_acquire_destroy(self):

            

Reported by Pylint.

Instance of 'BaseLockTests' has no 'locktype' member
Error

Line: 113 Column: 16

                      del lock

    def test_acquire_destroy(self):
        lock = self.locktype()
        lock.acquire()
        del lock

    def test_acquire_release(self):
        lock = self.locktype()

            

Reported by Pylint.

Instance of 'BaseLockTests' has no 'locktype' member
Error

Line: 118 Column: 16

                      del lock

    def test_acquire_release(self):
        lock = self.locktype()
        lock.acquire()
        lock.release()
        del lock

    def test_try_acquire(self):

            

Reported by Pylint.

Instance of 'BaseLockTests' has no 'locktype' member
Error

Line: 124 Column: 16

                      del lock

    def test_try_acquire(self):
        lock = self.locktype()
        self.assertTrue(lock.acquire(False))
        lock.release()

    def test_try_acquire_contended(self):
        lock = self.locktype()

            

Reported by Pylint.

Instance of 'BaseLockTests' has no 'locktype' member
Error

Line: 129 Column: 16

                      lock.release()

    def test_try_acquire_contended(self):
        lock = self.locktype()
        lock.acquire()
        result = []
        def f():
            result.append(lock.acquire(False))
        Bunch(f, 1).wait_for_finished()

            

Reported by Pylint.

Instance of 'BaseLockTests' has no 'locktype' member
Error

Line: 139 Column: 16

                      lock.release()

    def test_acquire_contended(self):
        lock = self.locktype()
        lock.acquire()
        N = 5
        def f():
            lock.acquire()
            lock.release()

            

Reported by Pylint.

Lib/test/test_generators.py
209 issues
Instance of 'BaseException' has no 'value' member
Error

Line: 44 Column: 26

                      except BaseException as _exc:
            exc = _exc
        self.assertIs(type(exc), StopIteration)
        self.assertEqual(exc.value, "PASSED")


class FinalizationTest(unittest.TestCase):

    def test_frame_resurrect(self):

            

Reported by Pylint.

Undefined variable 'frame'
Error

Line: 64 Column: 25

                      del g
        support.gc_collect()
        self.assertIs(wr(), None)
        self.assertTrue(frame)
        del frame
        support.gc_collect()

    def test_refcycle(self):
        # A generator caught in a refcycle gets finalized anyway.

            

Reported by Pylint.

Class 'gi_yieldfrom' has no 'gi_code' member
Error

Line: 515 Column: 26

              
        gen_b.send(None)
        self.assertEqual(inspect.getgeneratorstate(gen_b), inspect.GEN_SUSPENDED)
        self.assertEqual(gen_b.gi_yieldfrom.gi_code.co_name, 'a')

        gen_b.send(None)
        self.assertEqual(inspect.getgeneratorstate(gen_b), inspect.GEN_SUSPENDED)
        self.assertIsNone(gen_b.gi_yieldfrom)


            

Reported by Pylint.

Catching too general exception BaseException
Error

Line: 41 Column: 16

                      gen.send(None)
        try:
            _testcapi.raise_SIGINT_then_send_None(gen)
        except BaseException as _exc:
            exc = _exc
        self.assertIs(type(exc), StopIteration)
        self.assertEqual(exc.value, "PASSED")



            

Reported by Pylint.

Access to a protected member _getframe of a client class
Error

Line: 56 Column: 25

                          try:
                yield
            finally:
                frame = sys._getframe()

        g = gen()
        wr = weakref.ref(g)
        next(g)
        del g

            

Reported by Pylint.

Unused variable 'g'
Error

Line: 75 Column: 17

                      def gen():
            nonlocal finalized
            try:
                g = yield
                yield 1
            finally:
                finalized = True

        g = gen()

            

Reported by Pylint.

Catching too general exception Exception
Error

Line: 192 Column: 16

              
        try:
            raise ValueError()
        except Exception as exc:
            try:
                make.throw(exc)
            except Exception:
                pass


            

Reported by Pylint.

Catching too general exception Exception
Error

Line: 195 Column: 20

                      except Exception as exc:
            try:
                make.throw(exc)
            except Exception:
                pass

        next(make)
        with self.assertRaises(ValueError) as cm:
            next(make)

            

Reported by Pylint.

Catching too general exception Exception
Error

Line: 213 Column: 16

                      g = gen()
        try:
            raise ValueError
        except Exception:
            self.assertEqual(next(g), "done")
        self.assertEqual(sys.exc_info(), (None, None, None))

    def test_except_gen_except(self):
        def gen():

            

Reported by Pylint.

Catching too general exception Exception
Error

Line: 238 Column: 16

                      next(g)
        try:
            raise ValueError
        except Exception:
            next(g)

        self.assertEqual(next(g), "done")
        self.assertEqual(sys.exc_info(), (None, None, None))


            

Reported by Pylint.

Lib/test/test_smtpd.py
208 issues
Attribute 'extended_smtp' defined outside __init__
Error

Line: 391 Column: 9

                                       b'503 Duplicate HELO/EHLO\r\n')

    def test_HELO_parameter_rejected_when_extensions_not_enabled(self):
        self.extended_smtp = False
        self.write_line(b'HELO example')
        self.write_line(b'MAIL from:<foo@example.com> SIZE=1234')
        self.assertEqual(self.channel.socket.last,
                         b'501 Syntax: MAIL FROM: <address>\r\n')


            

Reported by Pylint.

Unused variable 'spam'
Error

Line: 723 Column: 13

              
    def test_attribute_deprecations(self):
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            spam = self.channel._SMTPChannel__server
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            self.channel._SMTPChannel__server = 'spam'
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            spam = self.channel._SMTPChannel__line
        with warnings_helper.check_warnings(('', DeprecationWarning)):

            

Reported by Pylint.

Access to a protected member _SMTPChannel__server of a client class
Error

Line: 723 Column: 20

              
    def test_attribute_deprecations(self):
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            spam = self.channel._SMTPChannel__server
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            self.channel._SMTPChannel__server = 'spam'
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            spam = self.channel._SMTPChannel__line
        with warnings_helper.check_warnings(('', DeprecationWarning)):

            

Reported by Pylint.

Access to a protected member _SMTPChannel__server of a client class
Error

Line: 725 Column: 13

                      with warnings_helper.check_warnings(('', DeprecationWarning)):
            spam = self.channel._SMTPChannel__server
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            self.channel._SMTPChannel__server = 'spam'
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            spam = self.channel._SMTPChannel__line
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            self.channel._SMTPChannel__line = 'spam'
        with warnings_helper.check_warnings(('', DeprecationWarning)):

            

Reported by Pylint.

Access to a protected member _SMTPChannel__line of a client class
Error

Line: 727 Column: 20

                      with warnings_helper.check_warnings(('', DeprecationWarning)):
            self.channel._SMTPChannel__server = 'spam'
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            spam = self.channel._SMTPChannel__line
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            self.channel._SMTPChannel__line = 'spam'
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            spam = self.channel._SMTPChannel__state
        with warnings_helper.check_warnings(('', DeprecationWarning)):

            

Reported by Pylint.

Access to a protected member _SMTPChannel__line of a client class
Error

Line: 729 Column: 13

                      with warnings_helper.check_warnings(('', DeprecationWarning)):
            spam = self.channel._SMTPChannel__line
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            self.channel._SMTPChannel__line = 'spam'
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            spam = self.channel._SMTPChannel__state
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            self.channel._SMTPChannel__state = 'spam'
        with warnings_helper.check_warnings(('', DeprecationWarning)):

            

Reported by Pylint.

Access to a protected member _SMTPChannel__state of a client class
Error

Line: 731 Column: 20

                      with warnings_helper.check_warnings(('', DeprecationWarning)):
            self.channel._SMTPChannel__line = 'spam'
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            spam = self.channel._SMTPChannel__state
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            self.channel._SMTPChannel__state = 'spam'
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            spam = self.channel._SMTPChannel__greeting
        with warnings_helper.check_warnings(('', DeprecationWarning)):

            

Reported by Pylint.

Access to a protected member _SMTPChannel__state of a client class
Error

Line: 733 Column: 13

                      with warnings_helper.check_warnings(('', DeprecationWarning)):
            spam = self.channel._SMTPChannel__state
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            self.channel._SMTPChannel__state = 'spam'
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            spam = self.channel._SMTPChannel__greeting
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            self.channel._SMTPChannel__greeting = 'spam'
        with warnings_helper.check_warnings(('', DeprecationWarning)):

            

Reported by Pylint.

Access to a protected member _SMTPChannel__greeting of a client class
Error

Line: 735 Column: 20

                      with warnings_helper.check_warnings(('', DeprecationWarning)):
            self.channel._SMTPChannel__state = 'spam'
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            spam = self.channel._SMTPChannel__greeting
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            self.channel._SMTPChannel__greeting = 'spam'
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            spam = self.channel._SMTPChannel__mailfrom
        with warnings_helper.check_warnings(('', DeprecationWarning)):

            

Reported by Pylint.

Access to a protected member _SMTPChannel__greeting of a client class
Error

Line: 737 Column: 13

                      with warnings_helper.check_warnings(('', DeprecationWarning)):
            spam = self.channel._SMTPChannel__greeting
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            self.channel._SMTPChannel__greeting = 'spam'
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            spam = self.channel._SMTPChannel__mailfrom
        with warnings_helper.check_warnings(('', DeprecationWarning)):
            self.channel._SMTPChannel__mailfrom = 'spam'
        with warnings_helper.check_warnings(('', DeprecationWarning)):

            

Reported by Pylint.

Lib/xml/dom/expatbuilder.py
208 issues
Instance of 'module' has no 'XML_CTYPE_ANY' member
Error

Line: 90 Column: 33

                  def isElementContent(self):
        if self._model:
            type = self._model[0]
            return type not in (expat.model.XML_CTYPE_ANY,
                                expat.model.XML_CTYPE_MIXED)
        else:
            return False

    def isEmpty(self):

            

Reported by Pylint.

Instance of 'module' has no 'XML_CTYPE_MIXED' member
Error

Line: 91 Column: 33

                      if self._model:
            type = self._model[0]
            return type not in (expat.model.XML_CTYPE_ANY,
                                expat.model.XML_CTYPE_MIXED)
        else:
            return False

    def isEmpty(self):
        if self._model:

            

Reported by Pylint.

Instance of 'module' has no 'XML_CTYPE_EMPTY' member
Error

Line: 97 Column: 38

              
    def isEmpty(self):
        if self._model:
            return self._model[0] == expat.model.XML_CTYPE_EMPTY
        else:
            return False

    def isId(self, aname):
        for info in self._attr_info:

            

Reported by Pylint.

An attribute defined in expatbuilder line 147 hides this method
Error

Line: 369 Column: 5

                      if node is not self.document.documentElement:
            self._finish_start_element(node)

    def _finish_start_element(self, node):
        if self._filter:
            # To be general, we'd have to call isSameNode(), but this
            # is sufficient for minidom:
            if node is self.document.documentElement:
                return

            

Reported by Pylint.

An attribute defined in expatbuilder line 266 hides this method
Error

Line: 397 Column: 5

                      self.curNode = curNode.parentNode
        self._finish_end_element(curNode)

    def _finish_end_element(self, curNode):
        info = self._elem_info.get(curNode.tagName)
        if info:
            self._handle_white_text_nodes(curNode, info)
        if self._filter:
            if curNode is self.document.documentElement:

            

Reported by Pylint.

Instance of 'FilterCrutch' has no 'start_element_handler' member
Error

Line: 523 Column: 38

                      parser = builder._parser
        self._old_start = parser.StartElementHandler
        self._old_end = parser.EndElementHandler
        parser.StartElementHandler = self.start_element_handler
        parser.EndElementHandler = self.end_element_handler

class Rejecter(FilterCrutch):
    __slots__ = ()


            

Reported by Pylint.

Instance of 'FilterCrutch' has no 'end_element_handler' member
Error

Line: 524 Column: 36

                      self._old_start = parser.StartElementHandler
        self._old_end = parser.EndElementHandler
        parser.StartElementHandler = self.start_element_handler
        parser.EndElementHandler = self.end_element_handler

class Rejecter(FilterCrutch):
    __slots__ = ()

    def __init__(self, builder):

            

Reported by Pylint.

Instance of 'Namespaces' has no '_options' member
Error

Line: 728 Column: 12

                  def install(self, parser):
        """Insert the namespace-handlers onto the parser."""
        ExpatBuilder.install(self, parser)
        if self._options.namespace_declarations:
            parser.StartNamespaceDeclHandler = (
                self.start_namespace_decl_handler)

    def start_namespace_decl_handler(self, prefix, uri):
        """Push this namespace declaration on our storage."""

            

Reported by Pylint.

Instance of 'Namespaces' has no 'document' member
Error

Line: 745 Column: 30

                          localname = None
            prefix = EMPTY_PREFIX
        node = minidom.Element(qname, uri, prefix, localname)
        node.ownerDocument = self.document
        _append_child(self.curNode, node)
        self.curNode = node

        if self._ns_ordered_prefixes:
            for prefix, uri in self._ns_ordered_prefixes:

            

Reported by Pylint.

Instance of 'Namespaces' has no 'document' member
Error

Line: 758 Column: 35

                                  a = minidom.Attr("xmlns", XMLNS_NAMESPACE,
                                     "xmlns", EMPTY_PREFIX)
                a.value = uri
                a.ownerDocument = self.document
                _set_attribute_node(node, a)
            del self._ns_ordered_prefixes[:]

        if attributes:
            node._ensure_attributes()

            

Reported by Pylint.

setup.py
208 issues
Starting a process with a shell, possible injection detected, security issue.
Security injection

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

              

def run_command(cmd):
    status = os.system(cmd)
    return os.waitstatus_to_exitcode(status)


# Set common compiler and linker flags derived from the Makefile,
# reserved for building the interpreter and the stdlib modules.

            

Reported by Bandit.

Module 'os' has no 'waitstatus_to_exitcode' member
Error

Line: 122 Column: 12

              
def run_command(cmd):
    status = os.system(cmd)
    return os.waitstatus_to_exitcode(status)


# Set common compiler and linker flags derived from the Makefile,
# reserved for building the interpreter and the stdlib modules.
# See bpo-21121 and bpo-35257

            

Reported by Pylint.

Redefining built-in 'dir'
Error

Line: 134 Column: 30

                  sysconfig.get_config_vars()[compiler_flags] = flags + ' ' + py_flags_nodist


def add_dir_to_list(dirlist, dir):
    """Add the directory 'dir' to the list 'dirlist' (after any relative
    directories) if:

    1) 'dir' is not already in 'dirlist'
    2) 'dir' actually exists, and is a directory.

            

Reported by Pylint.

Using the global statement
Error

Line: 191 Column: 5

                  setting of various variables; see the xcrun man page for more info.
    Also sets MACOS_SDK_SPECIFIED for use by macosx_sdk_specified().
    """
    global MACOS_SDK_ROOT, MACOS_SDK_SPECIFIED

    # If already called, return cached result.
    if MACOS_SDK_ROOT:
        return MACOS_SDK_ROOT


            

Reported by Pylint.

Access to a protected member _default_sysroot of a client class
Error

Line: 203 Column: 26

                      MACOS_SDK_ROOT = m.group(1)
        MACOS_SDK_SPECIFIED = MACOS_SDK_ROOT != '/'
    else:
        MACOS_SDK_ROOT = _osx_support._default_sysroot(
            sysconfig.get_config_var('CC'))
        MACOS_SDK_SPECIFIED = False

    return MACOS_SDK_ROOT


            

Reported by Pylint.

Using the global statement
Error

Line: 221 Column: 5

                  the implicit use of an SDK when header files are no longer
    installed on a running system by the Command Line Tools.
    """
    global MACOS_SDK_SPECIFIED

    # If already called, return cached result.
    if MACOS_SDK_SPECIFIED:
        return MACOS_SDK_SPECIFIED


            

Reported by Pylint.

Else clause on loop without a break statement
Error

Line: 338 Column: 5

              
        if p == dirname:
            return [p]
    else:
        assert False, "Internal error: Path not found in std_dirs or paths"


def validate_tzpath():
    base_tzpath = sysconfig.get_config_var('TZPATH')

            

Reported by Pylint.

Use lazy % formatting in logging functions
Error

Line: 362 Column: 9

                  if not dirs:
        return module
    if len(dirs) > 1:
        log.info(f"WARNING: multiple copies of {module} found")
    return os.path.join(dirs[0], module)


class PyBuildExt(build_ext):


            

Reported by Pylint.

Attribute 'extensions' defined outside __init__
Error

Line: 400 Column: 9

                      if "_ctypes" in ext_map:
            ctypes = extensions.pop(ext_map["_ctypes"])
            extensions.append(ctypes)
        self.extensions = extensions

    def update_sources_depends(self):
        # Fix up the autodetected modules, prefixing all the source files
        # with Modules/.
        moddirlist = [os.path.join(self.srcdir, 'Modules')]

            

Reported by Pylint.

Attribute 'extensions' defined outside __init__
Error

Line: 445 Column: 13

              
        mods_configured = mods_built + mods_disabled
        if mods_configured:
            self.extensions = [x for x in self.extensions if x not in
                               mods_configured]
            # Remove the shared libraries built by a previous build.
            for ext in mods_configured:
                fullpath = self.get_ext_fullpath(ext.name)
                if os.path.exists(fullpath):

            

Reported by Pylint.

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

Line: 10 Column: 1

              import sys
import sysconfig
import unittest
import traceback

from xml.parsers import expat
from xml.parsers.expat import errors

from test.support import sortdict

            

Reported by Pylint.

Instance of 'module' has no 'XML_ERROR_FINISHED' member
Error

Line: 273 Column: 27

                      with self.assertRaises(expat.error) as cm:
            parser.ParseFile(file)
        self.assertEqual(expat.ErrorString(cm.exception.code),
                          expat.errors.XML_ERROR_FINISHED)

class NamespaceSeparatorTest(unittest.TestCase):
    def test_legal(self):
        # Tests that make sure we get errors when the namespace_separator value
        # is illegal, and that we don't for good values:

            

Reported by Pylint.

Instance of 'module' has no 'XML_ERROR_SYNTAX' member
Error

Line: 667 Column: 26

              class ErrorMessageTest(unittest.TestCase):
    def test_codes(self):
        # verify mapping of errors.codes and errors.messages
        self.assertEqual(errors.XML_ERROR_SYNTAX,
                         errors.messages[errors.codes[errors.XML_ERROR_SYNTAX]])

    def test_expaterror(self):
        xml = b'<'
        parser = expat.ParserCreate()

            

Reported by Pylint.

Instance of 'module' has no 'codes' member
Error

Line: 668 Column: 42

                  def test_codes(self):
        # verify mapping of errors.codes and errors.messages
        self.assertEqual(errors.XML_ERROR_SYNTAX,
                         errors.messages[errors.codes[errors.XML_ERROR_SYNTAX]])

    def test_expaterror(self):
        xml = b'<'
        parser = expat.ParserCreate()
        try:

            

Reported by Pylint.

Instance of 'module' has no 'XML_ERROR_SYNTAX' member
Error

Line: 668 Column: 55

                  def test_codes(self):
        # verify mapping of errors.codes and errors.messages
        self.assertEqual(errors.XML_ERROR_SYNTAX,
                         errors.messages[errors.codes[errors.XML_ERROR_SYNTAX]])

    def test_expaterror(self):
        xml = b'<'
        parser = expat.ParserCreate()
        try:

            

Reported by Pylint.

Instance of 'module' has no 'messages' member
Error

Line: 668 Column: 26

                  def test_codes(self):
        # verify mapping of errors.codes and errors.messages
        self.assertEqual(errors.XML_ERROR_SYNTAX,
                         errors.messages[errors.codes[errors.XML_ERROR_SYNTAX]])

    def test_expaterror(self):
        xml = b'<'
        parser = expat.ParserCreate()
        try:

            

Reported by Pylint.

Instance of 'module' has no 'codes' member
Error

Line: 678 Column: 30

                          self.fail()
        except expat.ExpatError as e:
            self.assertEqual(e.code,
                             errors.codes[errors.XML_ERROR_UNCLOSED_TOKEN])


class ForeignDTDTests(unittest.TestCase):
    """
    Tests for the UseForeignDTD method of expat parser objects.

            

Reported by Pylint.

Instance of 'module' has no 'XML_ERROR_UNCLOSED_TOKEN' member
Error

Line: 678 Column: 43

                          self.fail()
        except expat.ExpatError as e:
            self.assertEqual(e.code,
                             errors.codes[errors.XML_ERROR_UNCLOSED_TOKEN])


class ForeignDTDTests(unittest.TestCase):
    """
    Tests for the UseForeignDTD method of expat parser objects.

            

Reported by Pylint.

XXX TypeErrors on calling handlers, or on bad return values from a
Error

Line: 1 Column: 3

              # XXX TypeErrors on calling handlers, or on bad return values from a
# handler, are obscure and unhelpful.

from io import BytesIO
import os
import platform
import sys
import sysconfig
import unittest

            

Reported by Pylint.

Statement seems to have no effect
Error

Line: 50 Column: 13

                      with self.assertRaises(AttributeError):
            self.parser.returns_unicode = 1
        with self.assertRaises(AttributeError):
            self.parser.returns_unicode

        # Issue #25019
        self.assertRaises(TypeError, setattr, self.parser, range(0xF), 0)
        self.assertRaises(TypeError, self.parser.__setattr__, range(0xF), 0)
        self.assertRaises(TypeError, getattr, self.parser, range(0xF))

            

Reported by Pylint.

Lib/test/test_zipimport.py
200 issues
Chmod setting a permissive mask 0o666 on file (TESTMOD).
Security

Line: 813
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b103_set_bad_file_permissions.html

                      finally:
            # If we leave "the read-only bit" set on Windows, nothing can
            # delete TESTMOD, and later tests suffer bogus failures.
            os.chmod(TESTMOD, 0o666)
            os_helper.unlink(TESTMOD)

    def testNotZipFile(self):
        os_helper.unlink(TESTMOD)
        fp = open(TESTMOD, 'w+')

            

Reported by Bandit.

Cannot import 'traceback' due to syntax error 'invalid syntax (<unknown>, line 576)'
Error

Line: 23 Column: 1

              import doctest
import inspect
import io
from traceback import extract_tb, extract_stack, print_tb
try:
    import zlib
except ImportError:
    zlib = None


            

Reported by Pylint.

Module 'zipimport' has no '_zip_directory_cache' member
Error

Line: 92 Column: 9

                      # We're reusing the zip archive path, so we must clear the
        # cached directory info and linecache.
        linecache.clearcache()
        zipimport._zip_directory_cache.clear()
        ImportHooksBaseTestCase.setUp(self)

    def makeTree(self, files, dirName=TEMP_DIR):
        # Create a filesystem based set of modules/packages
        # defined by files under the directory dirName.

            

Reported by Pylint.

Module 'zipimport' has no 'ZipImportError' member
Error

Line: 246 Column: 16

                      try:
            self.doTest(".py", files, TESTMOD)
            self.fail("This should not be reached")
        except zipimport.ZipImportError as exc:
            self.assertIsInstance(exc.__cause__, ImportError)
            self.assertIn("magic number", exc.__cause__.msg)

    def testBadMTime(self):
        badtime_pyc = bytearray(test_pyc)

            

Reported by Pylint.

Module 'zipimport' has no 'zipimporter' member
Error

Line: 452 Column: 14

                              zinfo.comment = b"spam"
                z.writestr(zinfo, data)

        zi = zipimport.zipimporter(TEMP_ZIP)
        self.assertEqual(zi.archive, TEMP_ZIP)
        self.assertTrue(zi.is_package(TESTPACK))

        # PEP 302
        with warnings.catch_warnings():

            

Reported by Pylint.

Module 'zipimport' has no 'zipimporter' member
Error

Line: 461 Column: 45

                          warnings.simplefilter("ignore", DeprecationWarning)
            find_mod = zi.find_module('spam')
            self.assertIsNotNone(find_mod)
            self.assertIsInstance(find_mod, zipimport.zipimporter)
            self.assertFalse(find_mod.is_package('spam'))
            load_mod = find_mod.load_module('spam')
            self.assertEqual(find_mod.get_filename('spam'), load_mod.__file__)

            mod = zi.load_module(TESTPACK)

            

Reported by Pylint.

Module 'zipimport' has no 'zipimporter' member
Error

Line: 472 Column: 44

                      # PEP 451
        spec = zi.find_spec('spam')
        self.assertIsNotNone(spec)
        self.assertIsInstance(spec.loader, zipimport.zipimporter)
        self.assertFalse(spec.loader.is_package('spam'))
        exec_mod = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(exec_mod)
        self.assertEqual(spec.loader.get_filename('spam'), exec_mod.__file__)


            

Reported by Pylint.

Module 'zipimport' has no 'zipimporter' member
Error

Line: 505 Column: 15

                      self.assertEqual(loader.get_filename(mod_name), mod.__file__)

        # test prefix and archivepath members
        zi2 = zipimport.zipimporter(TEMP_ZIP + os.sep + TESTPACK)
        self.assertEqual(zi2.archive, TEMP_ZIP)
        self.assertEqual(zi2.prefix, TESTPACK + os.sep)

    def testInvalidateCaches(self):
        packdir = TESTPACK + os.sep

            

Reported by Pylint.

Module 'zipimport' has no 'zipimporter' member
Error

Line: 524 Column: 14

                              zinfo.comment = b"spam"
                z.writestr(zinfo, data)

        zi = zipimport.zipimporter(TEMP_ZIP)
        self.assertEqual(zi._files.keys(), files.keys())
        # Check that the file information remains accurate after reloading
        zi.invalidate_caches()
        self.assertEqual(zi._files.keys(), files.keys())
        # Add a new file to the ZIP archive

            

Reported by Pylint.

Module 'zipimport' has no 'zipimporter' member
Error

Line: 543 Column: 44

                      self.assertEqual(zi._files.keys(), files.keys())
        spec = zi.find_spec('spam2')
        self.assertIsNotNone(spec)
        self.assertIsInstance(spec.loader, zipimport.zipimporter)
        # Check that the cached data is removed if the file is deleted
        os.remove(TEMP_ZIP)
        zi.invalidate_caches()
        self.assertIsNone(zi._files)
        self.assertIsNone(zipimport._zip_directory_cache.get(zi.archive))

            

Reported by Pylint.

Lib/test/mapping_tests.py
197 issues
self.type2test is not callable
Error

Line: 21 Column: 16

                      return {"1": "2", "key1":"value1", "key2":(1,2,3)}
    def _empty_mapping(self):
        """Return an empty mapping object"""
        return self.type2test()
    def _full_mapping(self, data):
        """Return a mapping object with the value contained in data
        dictionary"""
        x = self._empty_mapping()
        for key, value in data.items():

            

Reported by Pylint.

class already defined line 215
Error

Line: 222 Column: 9

              
        d.clear()

        class FailingUserDict:
            def keys(self):
                class BogonIter:
                    def __init__(self):
                        self.i = 1
                    def __iter__(self):

            

Reported by Pylint.

class already defined line 215
Error

Line: 239 Column: 9

                              return key
        self.assertRaises(Exc, d.update, FailingUserDict())

        class FailingUserDict:
            def keys(self):
                class BogonIter:
                    def __init__(self):
                        self.i = ord('a')
                    def __iter__(self):

            

Reported by Pylint.

self.type2test is not callable
Error

Line: 309 Column: 26

                  def test_constructor(self):
        BasicTestMappingProtocol.test_constructor(self)
        self.assertTrue(self._empty_mapping() is not self._empty_mapping())
        self.assertEqual(self.type2test(x=1, y=2), {"x": 1, "y": 2})

    def test_bool(self):
        BasicTestMappingProtocol.test_bool(self)
        self.assertTrue(not self._empty_mapping())
        self.assertTrue(self._full_mapping({"x": "y"}))

            

Reported by Pylint.

Inheriting 'self.type2test', which is not a class.
Error

Line: 434 Column: 9

                          yield 1
        self.assertEqual(d.fromkeys(g()), {1:None})
        self.assertRaises(TypeError, {}.fromkeys, 3)
        class dictlike(self.type2test): pass
        self.assertEqual(dictlike.fromkeys('a'), {'a':None})
        self.assertEqual(dictlike().fromkeys('a'), {'a':None})
        self.assertTrue(dictlike.fromkeys('a').__class__ is dictlike)
        self.assertTrue(dictlike().fromkeys('a').__class__ is dictlike)
        self.assertTrue(type(dictlike.fromkeys('a')) is dictlike)

            

Reported by Pylint.

Inheriting 'self.type2test', which is not a class.
Error

Line: 440 Column: 9

                      self.assertTrue(dictlike.fromkeys('a').__class__ is dictlike)
        self.assertTrue(dictlike().fromkeys('a').__class__ is dictlike)
        self.assertTrue(type(dictlike.fromkeys('a')) is dictlike)
        class mydict(self.type2test):
            def __new__(cls):
                return collections.UserDict()
        ud = mydict.fromkeys('ab')
        self.assertEqual(ud, {'a':None, 'b':None})
        self.assertIsInstance(ud, collections.UserDict)

            

Reported by Pylint.

Inheriting 'self.type2test', which is not a class.
Error

Line: 450 Column: 9

              
        class Exc(Exception): pass

        class baddict1(self.type2test):
            def __init__(self, *args, **kwargs):
                raise Exc()

        self.assertRaises(Exc, baddict1.fromkeys, [1])


            

Reported by Pylint.

Inheriting 'self.type2test', which is not a class.
Error

Line: 464 Column: 9

              
        self.assertRaises(Exc, self.type2test.fromkeys, BadSeq())

        class baddict2(self.type2test):
            def __setitem__(self, key, value):
                raise Exc()

        self.assertRaises(Exc, baddict2.fromkeys, [1])


            

Reported by Pylint.

Inheriting 'self.type2test', which is not a class.
Error

Line: 568 Column: 9

              
    def test_fromkeys(self):
        TestMappingProtocol.test_fromkeys(self)
        class mydict(self.type2test):
            def __new__(cls):
                return collections.UserDict()
        ud = mydict.fromkeys('ab')
        self.assertEqual(ud, {'a':None, 'b':None})
        self.assertIsInstance(ud, collections.UserDict)

            

Reported by Pylint.

Redefining built-in 'iter'
Error

Line: 72 Column: 31

                      if p: self.fail("Empty mapping must compare to False")
        if not d: self.fail("Full mapping must compare to True")
        # keys(), items(), iterkeys() ...
        def check_iterandlist(iter, lst, ref):
            self.assertTrue(hasattr(iter, '__next__'))
            self.assertTrue(hasattr(iter, '__iter__'))
            x = list(iter)
            self.assertTrue(set(x)==set(lst)==set(ref))
        check_iterandlist(iter(d.keys()), list(d.keys()),

            

Reported by Pylint.

Lib/zipfile.py
196 issues
Access to member '__names' before its definition line 2244
Error

Line: 2243 Column: 20

              
    def namelist(self):
        with contextlib.suppress(AttributeError):
            return self.__names
        self.__names = super(FastLookup, self).namelist()
        return self.__names

    def _name_set(self):
        with contextlib.suppress(AttributeError):

            

Reported by Pylint.

Access to member '__lookup' before its definition line 2250
Error

Line: 2249 Column: 20

              
    def _name_set(self):
        with contextlib.suppress(AttributeError):
            return self.__lookup
        self.__lookup = super(FastLookup, self)._name_set()
        return self.__lookup


class Path:

            

Reported by Pylint.

Unused variable 'reloff'
Error

Line: 254 Column: 18

                  data = fpin.read(sizeEndCentDir64Locator)
    if len(data) != sizeEndCentDir64Locator:
        return endrec
    sig, diskno, reloff, disks = struct.unpack(structEndArchive64Locator, data)
    if sig != stringEndArchive64Locator:
        return endrec

    if diskno != 0 or disks > 1:
        raise BadZipFile("zipfiles that span multiple disks are not supported")

            

Reported by Pylint.

Unused variable 'sz'
Error

Line: 266 Column: 10

                  data = fpin.read(sizeEndCentDir64)
    if len(data) != sizeEndCentDir64:
        return endrec
    sig, sz, create_version, read_version, disk_num, disk_dir, \
        dircount, dircount2, dirsize, diroffset = \
        struct.unpack(structEndArchive64, data)
    if sig != stringEndArchive64:
        return endrec


            

Reported by Pylint.

Unused variable 'read_version'
Error

Line: 266 Column: 30

                  data = fpin.read(sizeEndCentDir64)
    if len(data) != sizeEndCentDir64:
        return endrec
    sig, sz, create_version, read_version, disk_num, disk_dir, \
        dircount, dircount2, dirsize, diroffset = \
        struct.unpack(structEndArchive64, data)
    if sig != stringEndArchive64:
        return endrec


            

Reported by Pylint.

Unused variable 'create_version'
Error

Line: 266 Column: 14

                  data = fpin.read(sizeEndCentDir64)
    if len(data) != sizeEndCentDir64:
        return endrec
    sig, sz, create_version, read_version, disk_num, disk_dir, \
        dircount, dircount2, dirsize, diroffset = \
        struct.unpack(structEndArchive64, data)
    if sig != stringEndArchive64:
        return endrec


            

Reported by Pylint.

Attribute 'header_offset' defined outside __init__
Error

Line: 509 Column: 25

                                      data = data[8:]
                    if self.header_offset == 0xFFFF_FFFF:
                        field = "Header offset"
                        self.header_offset, = unpack('<Q', data[:8])
                except struct.error:
                    raise BadZipFile(f"Corrupt zip64 extra field. "
                                     f"{field} not found.") from None

            extra = extra[ln+4:]

            

Reported by Pylint.

Unused variable 'j'
Error

Line: 565 Column: 9

              
_crctable = None
def _gen_crc(crc):
    for j in range(8):
        if crc & 1:
            crc = (crc >> 1) ^ 0xEDB88320
        else:
            crc >>= 1
    return crc

            

Reported by Pylint.

Using the global statement
Error

Line: 585 Column: 5

                  key1 = 591751049
    key2 = 878082192

    global _crctable
    if _crctable is None:
        _crctable = list(map(_gen_crc, range(256)))
    crctable = _crctable

    def crc32(ch, crc):

            

Reported by Pylint.

Redefining name 'crc32' from outer scope (line 23)
Error

Line: 590 Column: 5

                      _crctable = list(map(_gen_crc, range(256)))
    crctable = _crctable

    def crc32(ch, crc):
        """Compute the CRC32 primitive on one byte."""
        return (crc >> 8) ^ crctable[(crc ^ ch) & 0xFF]

    def update_keys(c):
        nonlocal key0, key1, key2

            

Reported by Pylint.