The following issues were found

Lib/multiprocessing/reduction.py
38 issues
Attempted relative import beyond top-level package
Error

Line: 19 Column: 1

              import socket
import sys

from . import context

__all__ = ['send_handle', 'recv_handle', 'ForkingPickler', 'register', 'dump']


HAVE_SEND_HANDLE = (sys.platform == 'win32' or

            

Reported by Pylint.

Unable to import '_winapi'
Error

Line: 69 Column: 5

              if sys.platform == 'win32':
    # Windows
    __all__ += ['DupHandle', 'duplicate', 'steal_handle']
    import _winapi

    def duplicate(handle, target_process=None, inheritable=False,
                  *, source_process=None):
        '''Duplicate a handle.  (target_process is a handle not a pid!)'''
        current_process = _winapi.GetCurrentProcess()

            

Reported by Pylint.

Attempted relative import beyond top-level package
Error

Line: 197 Column: 13

                      if popen_obj is not None:
            return popen_obj.DupFd(popen_obj.duplicate_for_child(fd))
        elif HAVE_SEND_HANDLE:
            from . import resource_sharer
            return resource_sharer.DupFd(fd)
        else:
            raise ValueError('SCM_RIGHTS appears not to be available')

#

            

Reported by Pylint.

Attempted relative import beyond top-level package
Error

Line: 235 Column: 9

              
if sys.platform == 'win32':
    def _reduce_socket(s):
        from .resource_sharer import DupSocket
        return _rebuild_socket, (DupSocket(s),)
    def _rebuild_socket(ds):
        return ds.detach()
    register(socket.socket, _reduce_socket)


            

Reported by Pylint.

Redefining built-in 'type'
Error

Line: 44 Column: 23

                      self.dispatch_table.update(self._extra_reducers)

    @classmethod
    def register(cls, type, reduce):
        '''Register a reduce function for a type.'''
        cls._extra_reducers[type] = reduce

    @classmethod
    def dumps(cls, obj, protocol=None):

            

Reported by Pylint.

Unused variable 'addr'
Error

Line: 157 Column: 30

                      '''Receive an array of fds over an AF_UNIX socket.'''
        a = array.array('i')
        bytes_size = a.itemsize * size
        msg, ancdata, flags, addr = sock.recvmsg(1, socket.CMSG_SPACE(bytes_size))
        if not msg and not ancdata:
            raise EOFError
        try:
            if ACKNOWLEDGE:
                sock.send(b'A')

            

Reported by Pylint.

Unused variable 'flags'
Error

Line: 157 Column: 23

                      '''Receive an array of fds over an AF_UNIX socket.'''
        a = array.array('i')
        bytes_size = a.itemsize * size
        msg, ancdata, flags, addr = sock.recvmsg(1, socket.CMSG_SPACE(bytes_size))
        if not msg and not ancdata:
            raise EOFError
        try:
            if ACKNOWLEDGE:
                sock.send(b'A')

            

Reported by Pylint.

Unused argument 'destination_pid'
Error

Line: 181 Column: 35

                          pass
        raise RuntimeError('Invalid data received')

    def send_handle(conn, handle, destination_pid):
        '''Send a handle over a local connection.'''
        with socket.fromfd(conn.fileno(), socket.AF_UNIX, socket.SOCK_STREAM) as s:
            sendfds(s, [handle])

    def recv_handle(conn):

            

Reported by Pylint.

Redefining built-in 'type'
Error

Line: 245 Column: 37

                  def _reduce_socket(s):
        df = DupFd(s.fileno())
        return _rebuild_socket, (df, s.family, s.type, s.proto)
    def _rebuild_socket(df, family, type, proto):
        fd = df.detach()
        return socket.socket(family, type, proto, fileno=fd)
    register(socket.socket, _reduce_socket)



            

Reported by Pylint.

Unused argument 'args'
Error

Line: 276 Column: 1

                  _reduce_socket = _reduce_socket
    _rebuild_socket = _rebuild_socket

    def __init__(self, *args):
        register(type(_C().f), _reduce_method)
        register(type(list.append), _reduce_method_descriptor)
        register(type(int.__add__), _reduce_method_descriptor)
        register(functools.partial, _reduce_partial)
        register(socket.socket, _reduce_socket)

            

Reported by Pylint.

Lib/test/test_modulefinder.py
37 issues
Dangerous default value [] as argument
Error

Line: 322 Column: 5

                          ofi.close()

class ModuleFinderTest(unittest.TestCase):
    def _do_test(self, info, report=False, debug=0, replace_paths=[], modulefinder_class=modulefinder.ModuleFinder):
        import_this, modules, missing, maybe_missing, source = info
        create_package(source)
        try:
            mf = modulefinder_class(path=TEST_PATH, debug=debug,
                                           replace_paths=replace_paths)

            

Reported by Pylint.

Unused variable 'suffix'
Error

Line: 431 Column: 17

              
            def load_module(self, fqname, fp, pathname, file_info):
                # confirm that the fileinfo is a tuple of 3 elements
                suffix, mode, type = file_info
                return super().load_module(fqname, fp, pathname, file_info)

        self._do_test(absolute_import_test, modulefinder_class=CheckLoadModuleApi)

if __name__ == "__main__":

            

Reported by Pylint.

Unused variable 'type'
Error

Line: 431 Column: 31

              
            def load_module(self, fqname, fp, pathname, file_info):
                # confirm that the fileinfo is a tuple of 3 elements
                suffix, mode, type = file_info
                return super().load_module(fqname, fp, pathname, file_info)

        self._do_test(absolute_import_test, modulefinder_class=CheckLoadModuleApi)

if __name__ == "__main__":

            

Reported by Pylint.

Unused variable 'mode'
Error

Line: 431 Column: 25

              
            def load_module(self, fqname, fp, pathname, file_info):
                # confirm that the fileinfo is a tuple of 3 elements
                suffix, mode, type = file_info
                return super().load_module(fqname, fp, pathname, file_info)

        self._do_test(absolute_import_test, modulefinder_class=CheckLoadModuleApi)

if __name__ == "__main__":

            

Reported by Pylint.

Redefining built-in 'type'
Error

Line: 431 Column: 31

              
            def load_module(self, fqname, fp, pathname, file_info):
                # confirm that the fileinfo is a tuple of 3 elements
                suffix, mode, type = file_info
                return super().load_module(fqname, fp, pathname, file_info)

        self._do_test(absolute_import_test, modulefinder_class=CheckLoadModuleApi)

if __name__ == "__main__":

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import os
import errno
import importlib.machinery
import py_compile
import shutil
import unittest
import tempfile

from test import support

            

Reported by Pylint.

Line too long (106/100)
Error

Line: 256 Column: 1

                  """\
a_utf8.py
                                # use the default of utf8
                                print('Unicode test A code point 2090 \u2090 that is not valid in cp1252')
                                import b_utf8
b_utf8.py
                                # use the default of utf8
                                print('Unicode test B code point 2090 \u2090 that is not valid in cp1252')
"""]

            

Reported by Pylint.

Line too long (106/100)
Error

Line: 260 Column: 1

                                              import b_utf8
b_utf8.py
                                # use the default of utf8
                                print('Unicode test B code point 2090 \u2090 that is not valid in cp1252')
"""]

coding_explicit_utf8_test = [
    "a_utf8",
    ["a_utf8", "b_utf8"],

            

Reported by Pylint.

Line too long (106/100)
Error

Line: 270 Column: 1

                  """\
a_utf8.py
                                # coding=utf8
                                print('Unicode test A code point 2090 \u2090 that is not valid in cp1252')
                                import b_utf8
b_utf8.py
                                # use the default of utf8
                                print('Unicode test B code point 2090 \u2090 that is not valid in cp1252')
"""]

            

Reported by Pylint.

Line too long (106/100)
Error

Line: 274 Column: 1

                                              import b_utf8
b_utf8.py
                                # use the default of utf8
                                print('Unicode test B code point 2090 \u2090 that is not valid in cp1252')
"""]

coding_explicit_cp1252_test = [
    "a_cp1252",
    ["a_cp1252", "b_utf8"],

            

Reported by Pylint.

Lib/multiprocessing/sharedctypes.py
37 issues
Attempted relative import beyond top-level package
Error

Line: 13 Column: 1

              import ctypes
import weakref

from . import heap
from . import get_context

from .context import reduction, assert_spawning
_ForkingPickler = reduction.ForkingPickler


            

Reported by Pylint.

Attempted relative import beyond top-level package
Error

Line: 14 Column: 1

              import weakref

from . import heap
from . import get_context

from .context import reduction, assert_spawning
_ForkingPickler = reduction.ForkingPickler

__all__ = ['RawValue', 'RawArray', 'Value', 'Array', 'copy', 'synchronized']

            

Reported by Pylint.

Attempted relative import beyond top-level package
Error

Line: 16 Column: 1

              from . import heap
from . import get_context

from .context import reduction, assert_spawning
_ForkingPickler = reduction.ForkingPickler

__all__ = ['RawValue', 'RawArray', 'Value', 'Array', 'copy', 'synchronized']

#

            

Reported by Pylint.

Access to a protected member _SimpleCData of a client class
Error

Line: 107 Column: 24

                  assert not isinstance(obj, SynchronizedBase), 'object already synchronized'
    ctx = ctx or get_context()

    if isinstance(obj, ctypes._SimpleCData):
        return Synchronized(obj, lock, ctx)
    elif isinstance(obj, ctypes.Array):
        if obj._type_ is ctypes.c_char:
            return SynchronizedString(obj, lock, ctx)
        return SynchronizedArray(obj, lock, ctx)

            

Reported by Pylint.

Access to a protected member _type_ of a client class
Error

Line: 110 Column: 12

                  if isinstance(obj, ctypes._SimpleCData):
        return Synchronized(obj, lock, ctx)
    elif isinstance(obj, ctypes.Array):
        if obj._type_ is ctypes.c_char:
            return SynchronizedString(obj, lock, ctx)
        return SynchronizedArray(obj, lock, ctx)
    else:
        cls = type(obj)
        try:

            

Reported by Pylint.

Access to a protected member _fields_ of a client class
Error

Line: 118 Column: 44

                      try:
            scls = class_cache[cls]
        except KeyError:
            names = [field[0] for field in cls._fields_]
            d = {name: make_property(name) for name in names}
            classname = 'Synchronized' + cls.__name__
            scls = class_cache[cls] = type(classname, (SynchronizedBase,), d)
        return scls(obj, lock, ctx)


            

Reported by Pylint.

Access to a protected member _type_ of a client class
Error

Line: 131 Column: 32

              def reduce_ctype(obj):
    assert_spawning(obj)
    if isinstance(obj, ctypes.Array):
        return rebuild_ctype, (obj._type_, obj._wrapper, obj._length_)
    else:
        return rebuild_ctype, (type(obj), obj._wrapper, None)

def rebuild_ctype(type_, wrapper, length):
    if length is not None:

            

Reported by Pylint.

Access to a protected member _length_ of a client class
Error

Line: 131 Column: 58

              def reduce_ctype(obj):
    assert_spawning(obj)
    if isinstance(obj, ctypes.Array):
        return rebuild_ctype, (obj._type_, obj._wrapper, obj._length_)
    else:
        return rebuild_ctype, (type(obj), obj._wrapper, None)

def rebuild_ctype(type_, wrapper, length):
    if length is not None:

            

Reported by Pylint.

Access to a protected member _wrapper of a client class
Error

Line: 131 Column: 44

              def reduce_ctype(obj):
    assert_spawning(obj)
    if isinstance(obj, ctypes.Array):
        return rebuild_ctype, (obj._type_, obj._wrapper, obj._length_)
    else:
        return rebuild_ctype, (type(obj), obj._wrapper, None)

def rebuild_ctype(type_, wrapper, length):
    if length is not None:

            

Reported by Pylint.

Access to a protected member _wrapper of a client class
Error

Line: 133 Column: 43

                  if isinstance(obj, ctypes.Array):
        return rebuild_ctype, (obj._type_, obj._wrapper, obj._length_)
    else:
        return rebuild_ctype, (type(obj), obj._wrapper, None)

def rebuild_ctype(type_, wrapper, length):
    if length is not None:
        type_ = type_ * length
    _ForkingPickler.register(type_, reduce_ctype)

            

Reported by Pylint.

Lib/test/test_c_locale_coercion.py
37 issues
TODO: Once https://bugs.python.org/issue30672 is addressed, we'll be
Error

Line: 37 Column: 3

                  else:
        # Linux distros typically alias the POSIX locale directly to the C
        # locale.
        # TODO: Once https://bugs.python.org/issue30672 is addressed, we'll be
        #       able to check this case unconditionally
        EXPECTED_C_LOCALE_EQUIVALENTS.append("POSIX")
elif sys.platform.startswith("aix"):
    # AIX uses iso8859-1 in the C locale, other *nix platforms use ASCII
    EXPECTED_C_LOCALE_STREAM_ENCODING = "iso8859-1"

            

Reported by Pylint.

TODO: Work out a robust dynamic test for this that doesn't rely on
Error

Line: 49 Column: 3

                  EXPECTED_C_LOCALE_FS_ENCODING = "utf-8"
elif sys.platform == "cygwin":
    # Cygwin defaults to using C.UTF-8
    # TODO: Work out a robust dynamic test for this that doesn't rely on
    #       CPython's own locale handling machinery
    EXPECT_COERCION_IN_DEFAULT_LOCALE = False
elif sys.platform == "vxworks":
    # VxWorks defaults to using UTF-8 for all system interfaces
    EXPECTED_C_LOCALE_STREAM_ENCODING = "utf-8"

            

Reported by Pylint.

Unused variable 'py_cmd'
Error

Line: 93 Column: 13

                      # If there's no valid CODESET, we expect coercion to be skipped
        cmd_fmt += "; import sys; sys.exit(not locale.nl_langinfo(locale.CODESET))"
    cmd = cmd_fmt.format(locale_name)
    result, py_cmd = run_python_until_end("-c", cmd, PYTHONCOERCECLOCALE='')
    return result.rc == 0



_fields = "fsencoding stdin_info stdout_info stderr_info lang lc_ctype lc_all"

            

Reported by Pylint.

XXX (ncoghlan): Using JSON for child state reporting may be less fragile
Error

Line: 102 Column: 3

              _EncodingDetails = namedtuple("EncodingDetails", _fields)

class EncodingDetails(_EncodingDetails):
    # XXX (ncoghlan): Using JSON for child state reporting may be less fragile
    CHILD_PROCESS_SCRIPT = ";".join([
        "import sys, os",
        "print(sys.getfilesystemencoding())",
        "print(sys.stdin.encoding + ':' + sys.stdin.errors)",
        "print(sys.stdout.encoding + ':' + sys.stdout.errors)",

            

Reported by Pylint.

Using the global statement
Error

Line: 177 Column: 5

              CLI_COERCION_WARNING = None

def setUpModule():
    global AVAILABLE_TARGETS
    global CLI_COERCION_TARGET
    global CLI_COERCION_WARNING

    if AVAILABLE_TARGETS is not None:
        # initialization already done

            

Reported by Pylint.

Using the global statement
Error

Line: 178 Column: 5

              
def setUpModule():
    global AVAILABLE_TARGETS
    global CLI_COERCION_TARGET
    global CLI_COERCION_WARNING

    if AVAILABLE_TARGETS is not None:
        # initialization already done
        return

            

Reported by Pylint.

Using the global statement
Error

Line: 179 Column: 5

              def setUpModule():
    global AVAILABLE_TARGETS
    global CLI_COERCION_TARGET
    global CLI_COERCION_WARNING

    if AVAILABLE_TARGETS is not None:
        # initialization already done
        return
    AVAILABLE_TARGETS = []

            

Reported by Pylint.

XXX (ncoghlan): LANG=UTF-8 doesn't appear to work as
Error

Line: 263 Column: 3

                      }
        for env_var in ("LANG", "LC_CTYPE"):
            for locale_to_set in AVAILABLE_TARGETS:
                # XXX (ncoghlan): LANG=UTF-8 doesn't appear to work as
                #                 expected, so skip that combination for now
                # See https://bugs.python.org/issue30672 for discussion
                if env_var == "LANG" and locale_to_set == "UTF-8":
                    continue


            

Reported by Pylint.

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

Line: 423 Column: 15

                      # if it's not equal to "C"
        code = 'import locale; print(locale.setlocale(locale.LC_CTYPE, None))'
        env = dict(os.environ, PYTHONCOERCECLOCALE='1')
        cmd = subprocess.run([sys.executable, '-c', code],
                             stdout=subprocess.PIPE,
                             env=env,
                             text=True)
        self.assertEqual(cmd.stdout.rstrip(), loc)


            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              # Tests the attempted automatic coercion of the C locale to a UTF-8 locale

import locale
import os
import subprocess
import sys
import sysconfig
import unittest
from collections import namedtuple

            

Reported by Pylint.

Tools/c-analyzer/cpython/_analyzer.py
37 issues
Attempted relative import beyond top-level package
Error

Line: 29 Column: 1

              import c_analyzer as _c_analyzer
import c_analyzer.info as _info
import c_analyzer.datafiles as _datafiles
from . import _parser, REPO_ROOT


_DATA_DIR = os.path.dirname(__file__)
KNOWN_FILE = os.path.join(_DATA_DIR, 'known.tsv')
IGNORED_FILE = os.path.join(_DATA_DIR, 'ignored.tsv')

            

Reported by Pylint.

Undefined variable 'decls'
Error

Line: 82 Column: 27

              
def write_known():
    raise NotImplementedError
    datafiles.write_known(decls, IGNORED_FILE, ['unsupported'], relroot=REPO_ROOT)


def read_ignored():
    if not _IGNORED:
        _IGNORED.update(_datafiles.read_ignored(IGNORED_FILE, relroot=REPO_ROOT))

            

Reported by Pylint.

Undefined variable 'datafiles'
Error

Line: 82 Column: 5

              
def write_known():
    raise NotImplementedError
    datafiles.write_known(decls, IGNORED_FILE, ['unsupported'], relroot=REPO_ROOT)


def read_ignored():
    if not _IGNORED:
        _IGNORED.update(_datafiles.read_ignored(IGNORED_FILE, relroot=REPO_ROOT))

            

Reported by Pylint.

Undefined variable 'variables'
Error

Line: 93 Column: 30

              
def write_ignored():
    raise NotImplementedError
    _datafiles.write_ignored(variables, IGNORED_FILE, relroot=REPO_ROOT)


def analyze(filenames, *,
            skip_objects=False,
            **kwargs

            

Reported by Pylint.

Method should have "self" as first argument
Error

Line: 264 Column: 5

              class Analyzed(_info.Analyzed):

    @classonly
    def is_target(cls, raw):
        if not super().is_target(raw):
            return False
        if raw.kind not in KINDS:
            return False
        return True

            

Reported by Pylint.

Method should have "self" as first argument
Error

Line: 330 Column: 5

                  _item_class = Analyzed

    @classonly
    def build_item(cls, info, result=None):
        if not isinstance(info, Declaration) or info.kind not in KINDS:
            raise NotImplementedError((info, result))
        return super().build_item(info, result)



            

Reported by Pylint.

Unused import re
Error

Line: 2 Column: 1

              import os.path
import re

from c_common.clsutil import classonly
from c_parser.info import (
    KIND,
    DeclID,
    Declaration,
    TypeDeclaration,

            

Reported by Pylint.

Unused DeclID imported from c_parser.info
Error

Line: 5 Column: 1

              import re

from c_common.clsutil import classonly
from c_parser.info import (
    KIND,
    DeclID,
    Declaration,
    TypeDeclaration,
    TypeDef,

            

Reported by Pylint.

Unused TypeDef imported from c_parser.info
Error

Line: 5 Column: 1

              import re

from c_common.clsutil import classonly
from c_parser.info import (
    KIND,
    DeclID,
    Declaration,
    TypeDeclaration,
    TypeDef,

            

Reported by Pylint.

Unused Struct imported from c_parser.info
Error

Line: 5 Column: 1

              import re

from c_common.clsutil import classonly
from c_parser.info import (
    KIND,
    DeclID,
    Declaration,
    TypeDeclaration,
    TypeDef,

            

Reported by Pylint.

Lib/test/test_tools/test_i18n.py
37 issues
Else clause on loop without a break statement
Error

Line: 50 Column: 9

                              line = line[len('msgid '):]
                cur_msgid.append(line.strip('"'))
                reading_msgid = True
        else:
            if reading_msgid:
                msgids.append('\n'.join(cur_msgid))

        return msgids


            

Reported by Pylint.

Unused variable 'cwd'
Error

Line: 59 Column: 32

                  def extract_docstrings_from_str(self, module_content):
        """ utility: return all msgids extracted from module_content """
        filename = 'test_docstrings.py'
        with temp_cwd(None) as cwd:
            with open(filename, 'w') as fp:
                fp.write(module_content)
            assert_python_ok(self.script, '-D', filename)
            with open('messages.pot') as fp:
                data = fp.read()

            

Reported by Pylint.

Unused variable 'cwd'
Error

Line: 71 Column: 32

                      """Make sure the required fields are in the header, according to:
           http://www.gnu.org/software/gettext/manual/gettext.html#Header-Entry
        """
        with temp_cwd(None) as cwd:
            assert_python_ok(self.script)
            with open('messages.pot') as fp:
                data = fp.read()
            header = self.get_header(data)


            

Reported by Pylint.

Unused variable 'cwd'
Error

Line: 98 Column: 32

                  def test_POT_Creation_Date(self):
        """ Match the date format from xgettext for POT-Creation-Date """
        from datetime import datetime
        with temp_cwd(None) as cwd:
            assert_python_ok(self.script)
            with open('messages.pot') as fp:
                data = fp.read()
            header = self.get_header(data)
            creationDate = header['POT-Creation-Date']

            

Reported by Pylint.

Too many public methods (31/20)
Error

Line: 16 Column: 1

              skip_if_missing()


class Test_pygettext(unittest.TestCase):
    """Tests for the pygettext.py tool"""

    script = os.path.join(toolsdir,'i18n', 'pygettext.py')

    def get_header(self, data):

            

Reported by Pylint.

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

Line: 16 Column: 1

              skip_if_missing()


class Test_pygettext(unittest.TestCase):
    """Tests for the pygettext.py tool"""

    script = os.path.join(toolsdir,'i18n', 'pygettext.py')

    def get_header(self, data):

            

Reported by Pylint.

Method could be a function
Error

Line: 21 Column: 5

              
    script = os.path.join(toolsdir,'i18n', 'pygettext.py')

    def get_header(self, data):
        """ utility: return the header of a .po file as a dictionary """
        headers = {}
        for line in data.split('\n'):
            if not line or line.startswith(('#', 'msgid','msgstr')):
                continue

            

Reported by Pylint.

Method could be a function
Error

Line: 32 Column: 5

                          headers[key] = val.strip()
        return headers

    def get_msgids(self, data):
        """ utility: return all msgids in .po file as a list of strings """
        msgids = []
        reading_msgid = False
        cur_msgid = []
        for line in data.split('\n'):

            

Reported by Pylint.

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

Line: 60 Column: 41

                      """ utility: return all msgids extracted from module_content """
        filename = 'test_docstrings.py'
        with temp_cwd(None) as cwd:
            with open(filename, 'w') as fp:
                fp.write(module_content)
            assert_python_ok(self.script, '-D', filename)
            with open('messages.pot') as fp:
                data = fp.read()
        return self.get_msgids(data)

            

Reported by Pylint.

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

Line: 63 Column: 42

                          with open(filename, 'w') as fp:
                fp.write(module_content)
            assert_python_ok(self.script, '-D', filename)
            with open('messages.pot') as fp:
                data = fp.read()
        return self.get_msgids(data)

    def test_header(self):
        """Make sure the required fields are in the header, according to:

            

Reported by Pylint.

Lib/test/test_syntax.py
37 issues
method already defined line 1391
Error

Line: 1421 Column: 5

                      self._check_error("class C:\n  if 1: pass\n  else: return",
                          "outside function")

    def test_break_outside_loop(self):
        self._check_error("if 0: break",             "outside loop")
        self._check_error("if 0: break\nelse:  x=1",  "outside loop")
        self._check_error("if 1: pass\nelse: break", "outside loop")
        self._check_error("class C:\n  if 0: break", "outside loop")
        self._check_error("class C:\n  if 1: pass\n  else: break",

            

Reported by Pylint.

Too many lines in module (1556/1000)
Error

Line: 1 Column: 1

              """This module tests SyntaxErrors.

Here's an example of the sort of thing that is tested.

>>> def f(x):
...     global x
Traceback (most recent call last):
SyntaxError: name 'x' is parameter and global


            

Reported by Pylint.

Too many public methods (25/20)
Error

Line: 1301 Column: 1

              
from test import support

class SyntaxTestCase(unittest.TestCase):

    def _check_error(self, code, errtext,
                     filename="<testcase>", mode="exec", subclass=None, lineno=None, offset=None):
        """Check that compiling code raises SyntaxError with errtext.


            

Reported by Pylint.

Missing class docstring
Error

Line: 1301 Column: 1

              
from test import support

class SyntaxTestCase(unittest.TestCase):

    def _check_error(self, code, errtext,
                     filename="<testcase>", mode="exec", subclass=None, lineno=None, offset=None):
        """Check that compiling code raises SyntaxError with errtext.


            

Reported by Pylint.

Too many arguments (8/5)
Error

Line: 1303 Column: 5

              
class SyntaxTestCase(unittest.TestCase):

    def _check_error(self, code, errtext,
                     filename="<testcase>", mode="exec", subclass=None, lineno=None, offset=None):
        """Check that compiling code raises SyntaxError with errtext.

        errtest is a regular expression that must be present in the
        test of the exception raised.  If subclass is specified it

            

Reported by Pylint.

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

Line: 1316 Column: 13

                      except SyntaxError as err:
            if subclass and not isinstance(err, subclass):
                self.fail("SyntaxError is not a %s" % subclass.__name__)
            mo = re.search(errtext, str(err))
            if mo is None:
                self.fail("SyntaxError did not contain %r" % (errtext,))
            self.assertEqual(err.filename, filename)
            if lineno is not None:
                self.assertEqual(err.lineno, lineno)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 1327 Column: 5

                      else:
            self.fail("compile() did not raise SyntaxError")

    def test_expression_with_assignment(self):
        self._check_error(
            "print(end1 + end2 = ' ')",
            'expression cannot contain assignment, perhaps you meant "=="?',
            offset=7
        )

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 1334 Column: 5

                          offset=7
        )

    def test_curly_brace_after_primary_raises_immediately(self):
        self._check_error("f{}", "invalid syntax", mode="single")

    def test_assign_call(self):
        self._check_error("f() = 1", "assign")


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 1337 Column: 5

                  def test_curly_brace_after_primary_raises_immediately(self):
        self._check_error("f{}", "invalid syntax", mode="single")

    def test_assign_call(self):
        self._check_error("f() = 1", "assign")

    def test_assign_del(self):
        self._check_error("del (,)", "invalid syntax")
        self._check_error("del 1", "cannot delete literal")

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 1340 Column: 5

                  def test_assign_call(self):
        self._check_error("f() = 1", "assign")

    def test_assign_del(self):
        self._check_error("del (,)", "invalid syntax")
        self._check_error("del 1", "cannot delete literal")
        self._check_error("del (1, 2)", "cannot delete literal")
        self._check_error("del None", "cannot delete None")
        self._check_error("del *x", "cannot delete starred")

            

Reported by Pylint.

Lib/test/test_urllibnet.py
37 issues
XXX this test doesn't seem to test anything useful.
Error

Line: 19 Column: 3

              

class URLTimeoutTest(unittest.TestCase):
    # XXX this test doesn't seem to test anything useful.

    def setUp(self):
        socket.setdefaulttimeout(support.INTERNET_TIMEOUT)

    def tearDown(self):

            

Reported by Pylint.

Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.
Security blacklist

Line: 33
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b310-urllib-urlopen

              
        domain = urllib.parse.urlparse(support.TEST_HTTP_URL).netloc
        with socket_helper.transient_internet(domain):
            f = urllib.request.urlopen(support.TEST_HTTP_URL)
            f.read()


class urlopenNetworkTests(unittest.TestCase):
    """Tests urllib.request.urlopen using the network.

            

Reported by Bandit.

Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.
Security blacklist

Line: 62
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b310-urllib-urlopen

                  def urlopen(self, *args, **kwargs):
        resource = args[0]
        with socket_helper.transient_internet(resource):
            r = urllib.request.urlopen(*args, **kwargs)
            try:
                yield r
            finally:
                r.close()


            

Reported by Bandit.

Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.
Security blacklist

Line: 105
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b310-urllib-urlopen

                      URL = self.url + "XXXinvalidXXX"
        with socket_helper.transient_internet(URL):
            with self.assertWarns(DeprecationWarning):
                open_url = urllib.request.FancyURLopener().open(URL)
            try:
                code = open_url.getcode()
            finally:
                open_url.close()
            self.assertEqual(code, 404)

            

Reported by Bandit.

Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.
Security blacklist

Line: 148
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b310-urllib-urlopen

                                             'can be caused by a broken DNS server '
                               '(e.g. returns 404 or hijacks page)')
        with self.assertRaises(OSError, msg=failure_explanation):
            urllib.request.urlopen("http://{}/".format(bogus_domain))


class urlretrieveNetworkTests(unittest.TestCase):
    """Tests urllib.request.urlretrieve using the network."""


            

Reported by Bandit.

Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.
Security blacklist

Line: 162
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b310-urllib-urlopen

                  def urlretrieve(self, *args, **kwargs):
        resource = args[0]
        with socket_helper.transient_internet(resource):
            file_location, info = urllib.request.urlretrieve(*args, **kwargs)
            try:
                yield file_location, info
            finally:
                os_helper.unlink(file_location)


            

Reported by Bandit.

Unused variable 'info'
Error

Line: 170 Column: 61

              
    def test_basic(self):
        # Test basic functionality.
        with self.urlretrieve(self.logo) as (file_location, info):
            self.assertTrue(os.path.exists(file_location), "file location returned by"
                            " urlretrieve is not a valid path")
            with open(file_location, 'rb') as f:
                self.assertTrue(f.read(), "reading from the file location returned"
                                " by urlretrieve failed")

            

Reported by Pylint.

Unused variable 'info'
Error

Line: 180 Column: 68

                  def test_specified_path(self):
        # Make sure that specifying the location of the file to write to works.
        with self.urlretrieve(self.logo,
                              os_helper.TESTFN) as (file_location, info):
            self.assertEqual(file_location, os_helper.TESTFN)
            self.assertTrue(os.path.exists(file_location))
            with open(file_location, 'rb') as f:
                self.assertTrue(f.read(), "reading from temporary file failed")


            

Reported by Pylint.

Unused variable 'file_location'
Error

Line: 188 Column: 46

              
    def test_header(self):
        # Make sure header returned as 2nd value from urlretrieve is good.
        with self.urlretrieve(self.logo) as (file_location, info):
            self.assertIsInstance(info, email.message.Message,
                                  "info is not an instance of email.message.Message")

    logo = "http://www.pythontest.net/"


            

Reported by Pylint.

Unused variable 'file_location'
Error

Line: 195 Column: 46

                  logo = "http://www.pythontest.net/"

    def test_data_header(self):
        with self.urlretrieve(self.logo) as (file_location, fileheaders):
            datevalue = fileheaders.get('Date')
            dateformat = '%a, %d %b %Y %H:%M:%S GMT'
            try:
                time.strptime(datevalue, dateformat)
            except ValueError:

            

Reported by Pylint.

Lib/test/test_xxlimited.py
37 issues
Instance of 'CommonTests' has no 'assertRaises' member
Error

Line: 17 Column: 14

              
    def test_xxo_attributes(self):
        xxo = self.module.Xxo()
        with self.assertRaises(AttributeError):
            xxo.foo
        with self.assertRaises(AttributeError):
            del xxo.foo

        xxo.foo = 1234

            

Reported by Pylint.

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

Line: 19 Column: 14

                      xxo = self.module.Xxo()
        with self.assertRaises(AttributeError):
            xxo.foo
        with self.assertRaises(AttributeError):
            del xxo.foo

        xxo.foo = 1234
        self.assertEqual(xxo.foo, 1234)


            

Reported by Pylint.

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

Line: 23 Column: 9

                          del xxo.foo

        xxo.foo = 1234
        self.assertEqual(xxo.foo, 1234)

        del xxo.foo
        with self.assertRaises(AttributeError):
            xxo.foo


            

Reported by Pylint.

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

Line: 26 Column: 14

                      self.assertEqual(xxo.foo, 1234)

        del xxo.foo
        with self.assertRaises(AttributeError):
            xxo.foo

    def test_foo(self):
        # the foo function adds 2 numbers
        self.assertEqual(self.module.foo(1, 2), 3)

            

Reported by Pylint.

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

Line: 31 Column: 9

              
    def test_foo(self):
        # the foo function adds 2 numbers
        self.assertEqual(self.module.foo(1, 2), 3)

    def test_str(self):
        self.assertTrue(issubclass(self.module.Str, str))
        self.assertIsNot(self.module.Str, str)


            

Reported by Pylint.

Instance of 'CommonTests' has no 'assertTrue' member
Error

Line: 34 Column: 9

                      self.assertEqual(self.module.foo(1, 2), 3)

    def test_str(self):
        self.assertTrue(issubclass(self.module.Str, str))
        self.assertIsNot(self.module.Str, str)

        custom_string = self.module.Str("abcd")
        self.assertEqual(custom_string, "abcd")
        self.assertEqual(custom_string.upper(), "ABCD")

            

Reported by Pylint.

Instance of 'CommonTests' has no 'assertIsNot' member
Error

Line: 35 Column: 9

              
    def test_str(self):
        self.assertTrue(issubclass(self.module.Str, str))
        self.assertIsNot(self.module.Str, str)

        custom_string = self.module.Str("abcd")
        self.assertEqual(custom_string, "abcd")
        self.assertEqual(custom_string.upper(), "ABCD")


            

Reported by Pylint.

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

Line: 38 Column: 9

                      self.assertIsNot(self.module.Str, str)

        custom_string = self.module.Str("abcd")
        self.assertEqual(custom_string, "abcd")
        self.assertEqual(custom_string.upper(), "ABCD")

    def test_new(self):
        xxo = self.module.new()
        self.assertEqual(xxo.demo("abc"), "abc")

            

Reported by Pylint.

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

Line: 39 Column: 9

              
        custom_string = self.module.Str("abcd")
        self.assertEqual(custom_string, "abcd")
        self.assertEqual(custom_string.upper(), "ABCD")

    def test_new(self):
        xxo = self.module.new()
        self.assertEqual(xxo.demo("abc"), "abc")


            

Reported by Pylint.

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

Line: 43 Column: 9

              
    def test_new(self):
        xxo = self.module.new()
        self.assertEqual(xxo.demo("abc"), "abc")


class TestXXLimited(CommonTests, unittest.TestCase):
    module = xxlimited


            

Reported by Pylint.

Modules/socketmodule.c
37 issues
char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 313 Column: 11 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

                 https://msdn.microsoft.com/en-us/library/windows/desktop/ms738596.aspx */
typedef struct {
    DWORD build_number;  /* available starting with this Win10 BuildNumber */
    const char flag_name[20];
} FlagRuntimeInfo;

/* IMPORTANT: make sure the list ordered by descending build_number */
static FlagRuntimeInfo win_runtime_flags[] = {
    /* available starting with Windows 10 1709 */

            

Reported by FlawFinder.

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

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

                      }
        if (res->ai_addrlen < addr_ret_size)
            addr_ret_size = res->ai_addrlen;
        memcpy(addr_ret, res->ai_addr, addr_ret_size);
        freeaddrinfo(res);
        return siz;
    }
    /* special-case broadcast - inet_addr() below can return INADDR_NONE for
     * this */

            

Reported by FlawFinder.

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

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

                  }
    if (res->ai_addrlen < addr_ret_size)
        addr_ret_size = res->ai_addrlen;
    memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
    freeaddrinfo(res);
    switch (addr_ret->sa_family) {
    case AF_INET:
        return 4;
#ifdef ENABLE_IPV6

            

Reported by FlawFinder.

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

Line: 1193 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 PyObject *
make_ipv4_addr(const struct sockaddr_in *addr)
{
    char buf[INET_ADDRSTRLEN];
    if (inet_ntop(AF_INET, &addr->sin_addr, buf, sizeof(buf)) == NULL) {
        PyErr_SetFromErrno(PyExc_OSError);
        return NULL;
    }
    return PyUnicode_FromString(buf);

            

Reported by FlawFinder.

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

Line: 1207 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 PyObject *
make_ipv6_addr(const struct sockaddr_in6 *addr)
{
    char buf[INET6_ADDRSTRLEN];
    if (inet_ntop(AF_INET6, &addr->sin6_addr, buf, sizeof(buf)) == NULL) {
        PyErr_SetFromErrno(PyExc_OSError);
        return NULL;
    }
    return PyUnicode_FromString(buf);

            

Reported by FlawFinder.

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

Line: 1262 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 PyObject *
makebdaddr(bdaddr_t *bdaddr)
{
    char buf[(6 * 2) + 5 + 1];

#ifdef MS_WINDOWS
    int i;
    unsigned int octets[6];


            

Reported by FlawFinder.

sprintf - Does not check for buffer overflows
Security

Line: 1272 Column: 5 CWE codes: 120
Suggestion: Use sprintf_s, snprintf, or vsnprintf

                      octets[i] = ((*bdaddr) >> (8 * i)) & 0xFF;
    }

    sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
        octets[5], octets[4], octets[3],
        octets[2], octets[1], octets[0]);
#else
    sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
        bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],

            

Reported by FlawFinder.

sprintf - Does not check for buffer overflows
Security

Line: 1276 Column: 5 CWE codes: 120
Suggestion: Use sprintf_s, snprintf, or vsnprintf

                      octets[5], octets[4], octets[3],
        octets[2], octets[1], octets[0]);
#else
    sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
        bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
        bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
#endif

    return PyUnicode_FromString(buf);

            

Reported by FlawFinder.

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

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

                          addr->sun_path[path.len] = 0;
        }
        addr->sun_family = s->sock_family;
        memcpy(addr->sun_path, path.buf, path.len);
        *len_ret = path.len + offsetof(struct sockaddr_un, sun_path);
        retval = 1;
    unix_out:
        PyBuffer_Release(&path);
        Py_DECREF(args);

            

Reported by FlawFinder.

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

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

                      addr->sll_pkttype = pkttype;
        addr->sll_hatype = hatype;
        if (haddr.buf) {
            memcpy(&addr->sll_addr, haddr.buf, haddr.len);
            addr->sll_halen = haddr.len;
        }
        else
            addr->sll_halen = 0;
        *len_ret = sizeof *addr;

            

Reported by FlawFinder.