The following issues were found

Tools/scripts/combinerefs.py
10 issues
Missing function or method docstring
Error

Line: 81 Column: 1

              # that doesn't match pat (when whilematch is true), or that does match pat
# (when whilematch is false), is lost, and fileiter will resume at the line
# following it.
def read(fileiter, pat, whilematch):
    for line in fileiter:
        if bool(pat.match(line)) == whilematch:
            yield line
        else:
            break

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 88 Column: 1

                      else:
            break

def combinefile(f):
    fi = iter(f)

    for line in read(fi, re.compile(r'^Remaining objects:$'), False):
        pass


            

Reported by Pylint.

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

Line: 88 Column: 1

                      else:
            break

def combinefile(f):
    fi = iter(f)

    for line in read(fi, re.compile(r'^Remaining objects:$'), False):
        pass


            

Reported by Pylint.

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

Line: 89 Column: 5

                          break

def combinefile(f):
    fi = iter(f)

    for line in read(fi, re.compile(r'^Remaining objects:$'), False):
        pass

    crack = re.compile(r'([a-zA-Z\d]+) \[(\d+)\] (.*)')

            

Reported by Pylint.

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

Line: 99 Column: 9

                  addr2guts = {}
    before = 0
    for line in read(fi, re.compile(r'^Remaining object addresses:$'), False):
        m = crack.match(line)
        if m:
            addr, addr2rc[addr], addr2guts[addr] = m.groups()
            before += 1
        else:
            print('??? skipped:', line)

            

Reported by Pylint.

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

Line: 109 Column: 9

                  after = 0
    for line in read(fi, crack, True):
        after += 1
        m = crack.match(line)
        assert m
        addr, rc, guts = m.groups() # guts is type name here
        if addr not in addr2rc:
            print('??? new object created while tearing down:', line.rstrip())
            continue

            

Reported by Pylint.

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

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

                  for line in read(fi, crack, True):
        after += 1
        m = crack.match(line)
        assert m
        addr, rc, guts = m.groups() # guts is type name here
        if addr not in addr2rc:
            print('??? new object created while tearing down:', line.rstrip())
            continue
        print(addr, end=' ')

            

Reported by Bandit.

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

Line: 111 Column: 15

                      after += 1
        m = crack.match(line)
        assert m
        addr, rc, guts = m.groups() # guts is type name here
        if addr not in addr2rc:
            print('??? new object created while tearing down:', line.rstrip())
            continue
        print(addr, end=' ')
        if rc == addr2rc[addr]:

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 124 Column: 1

              
    print("%d objects before, %d after" % (before, after))

def combine(fname):
    with open(fname) as f:
        combinefile(f)

if __name__ == '__main__':
    combine(sys.argv[1])

            

Reported by Pylint.

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

Line: 125 Column: 25

                  print("%d objects before, %d after" % (before, after))

def combine(fname):
    with open(fname) as f:
        combinefile(f)

if __name__ == '__main__':
    combine(sys.argv[1])

            

Reported by Pylint.

Tools/scripts/parse_html5_entities.py
10 issues
Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.
Security blacklist

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

              
def get_json(url):
    """Download the json file from the url and returns a decoded object."""
    with urlopen(url) as f:
        data = f.read().decode('utf-8')
    return json.loads(data)

def create_dict(entities):
    """Create the html5 dict from the decoded json object."""

            

Reported by Bandit.

Redefining name 'new_html5' from outer scope (line 75)
Error

Line: 27 Column: 5

              
def create_dict(entities):
    """Create the html5 dict from the decoded json object."""
    new_html5 = {}
    for name, value in entities.items():
        new_html5[name.lstrip('&')] = value['characters']
    return new_html5

def compare_dicts(old, new):

            

Reported by Pylint.

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

Line: 17 Column: 1

              from urllib.request import urlopen
from html.entities import html5

entities_url = 'http://dev.w3.org/html5/spec/entities.json'

def get_json(url):
    """Download the json file from the url and returns a decoded object."""
    with urlopen(url) as f:
        data = f.read().decode('utf-8')

            

Reported by Pylint.

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

Line: 21 Column: 26

              
def get_json(url):
    """Download the json file from the url and returns a decoded object."""
    with urlopen(url) as f:
        data = f.read().decode('utf-8')
    return json.loads(data)

def create_dict(entities):
    """Create the html5 dict from the decoded json object."""

            

Reported by Pylint.

Unnecessary parens after 'in' keyword
Error

Line: 45 Column: 1

                      for name in sorted(removed):
            print('  {!r}: {!r}'.format(name, old[name]))
    changed = set()
    for name in (old.keys() & new.keys()):
        if old[name] != new[name]:
            changed.add((name, old[name], new[name]))
    if changed:
        print('{} entitie(s) have been modified:'.format(len(changed)))
        for item in sorted(changed):

            

Reported by Pylint.

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

Line: 82 Column: 9

                      print('# Generated by {}.  Do not edit manually.'.format(__file__))
        write_items(new_html5)
    elif '--patch' in sys.argv:
        fname = 'Lib/html/entities.py'
        temp_fname = fname + '.temp'
        with open(fname) as f1, open(temp_fname, 'w') as f2:
            skip = False
            for line in f1:
                if line.startswith('html5 = {'):

            

Reported by Pylint.

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

Line: 83 Column: 9

                      write_items(new_html5)
    elif '--patch' in sys.argv:
        fname = 'Lib/html/entities.py'
        temp_fname = fname + '.temp'
        with open(fname) as f1, open(temp_fname, 'w') as f2:
            skip = False
            for line in f1:
                if line.startswith('html5 = {'):
                    write_items(new_html5, file=f2)

            

Reported by Pylint.

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

Line: 85 Column: 13

                      fname = 'Lib/html/entities.py'
        temp_fname = fname + '.temp'
        with open(fname) as f1, open(temp_fname, 'w') as f2:
            skip = False
            for line in f1:
                if line.startswith('html5 = {'):
                    write_items(new_html5, file=f2)
                    skip = True
                    continue

            

Reported by Pylint.

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

Line: 89 Column: 21

                          for line in f1:
                if line.startswith('html5 = {'):
                    write_items(new_html5, file=f2)
                    skip = True
                    continue
                if skip:
                    # skip the old items until the }
                    if line.startswith('}'):
                        skip = False

            

Reported by Pylint.

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

Line: 94 Column: 25

                              if skip:
                    # skip the old items until the }
                    if line.startswith('}'):
                        skip = False
                    continue
                f2.write(line)
        os.remove(fname)
        os.rename(temp_fname, fname)
    else:

            

Reported by Pylint.

Tools/peg_generator/scripts/joinstats.py
9 issues
Redefining built-in 'type'
Error

Line: 31 Column: 27

                          for line in f:
                match = re.match(r"#define (\w+)_type (\d+)", line)
                if match:
                    name, type = match.groups()
                    if "left" in line.lower():
                        name += " // Left-recursive"
                    self.table[int(type)] = name

    def lookup(self, type: int) -> str:

            

Reported by Pylint.

Redefining built-in 'type'
Error

Line: 36 Column: 22

                                      name += " // Left-recursive"
                    self.table[int(type)] = name

    def lookup(self, type: int) -> str:
        return self.table.get(type, str(type))


def main() -> None:
    mapper = TypeMapper(parse_c)

            

Reported by Pylint.

Redefining built-in 'type'
Error

Line: 55 Column: 17

                              print(f"{lineno}: bad input ({line!r})")
                continue
            try:
                type, count = map(int, parts[:2])
            except ValueError as err:
                print(f"{lineno}: non-integer input ({line!r})")
                continue
            table.append((type, count))
    table.sort(key=lambda values: -values[1])

            

Reported by Pylint.

Unused variable 'err'
Error

Line: 56 Column: 13

                              continue
            try:
                type, count = map(int, parts[:2])
            except ValueError as err:
                print(f"{lineno}: non-integer input ({line!r})")
                continue
            table.append((type, count))
    table.sort(key=lambda values: -values[1])
    for type, count in table:

            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 22 Column: 1

              parse_c = os.path.join(reporoot, "peg_extension", "parse.c")


class TypeMapper:
    """State used to map types to names."""

    def __init__(self, filename: str) -> None:
        self.table: Dict[int, str] = {}
        with open(filename) as f:

            

Reported by Pylint.

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

Line: 27 Column: 32

              
    def __init__(self, filename: str) -> None:
        self.table: Dict[int, str] = {}
        with open(filename) as f:
            for line in f:
                match = re.match(r"#define (\w+)_type (\d+)", line)
                if match:
                    name, type = match.groups()
                    if "left" in line.lower():

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 36 Column: 5

                                      name += " // Left-recursive"
                    self.table[int(type)] = name

    def lookup(self, type: int) -> str:
        return self.table.get(type, str(type))


def main() -> None:
    mapper = TypeMapper(parse_c)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 40 Column: 1

                      return self.table.get(type, str(type))


def main() -> None:
    mapper = TypeMapper(parse_c)
    table = []
    filename = sys.argv[1]
    with open(filename) as f:
        for lineno, line in enumerate(f, 1):

            

Reported by Pylint.

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

Line: 44 Column: 28

                  mapper = TypeMapper(parse_c)
    table = []
    filename = sys.argv[1]
    with open(filename) as f:
        for lineno, line in enumerate(f, 1):
            line = line.strip()
            if not line or line.startswith("#"):
                continue
            parts = line.split()

            

Reported by Pylint.

Lib/test/test_spwd.py
9 issues
Unused variable 'cm'
Error

Line: 67 Column: 56

                  def test_getspnam_exception(self):
        name = 'bin'
        try:
            with self.assertRaises(PermissionError) as cm:
                spwd.getspnam(name)
        except KeyError as exc:
            self.skipTest("spwd entry %r doesn't exist: %s" % (name, exc))



            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import os
import unittest
from test.support import import_helper


spwd = import_helper.import_module('spwd')


@unittest.skipUnless(hasattr(os, 'geteuid') and os.geteuid() == 0,

            

Reported by Pylint.

Missing class docstring
Error

Line: 11 Column: 1

              
@unittest.skipUnless(hasattr(os, 'geteuid') and os.geteuid() == 0,
                     'root privileges required')
class TestSpwdRoot(unittest.TestCase):

    def test_getspall(self):
        entries = spwd.getspall()
        self.assertIsInstance(entries, list)
        for entry in entries:

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 13 Column: 5

                                   'root privileges required')
class TestSpwdRoot(unittest.TestCase):

    def test_getspall(self):
        entries = spwd.getspall()
        self.assertIsInstance(entries, list)
        for entry in entries:
            self.assertIsInstance(entry, spwd.struct_spwd)


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 19 Column: 5

                      for entry in entries:
            self.assertIsInstance(entry, spwd.struct_spwd)

    def test_getspnam(self):
        entries = spwd.getspall()
        if not entries:
            self.skipTest('empty shadow password database')
        random_name = entries[0].sp_namp
        entry = spwd.getspnam(random_name)

            

Reported by Pylint.

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

Line: 46 Column: 45

                      self.assertEqual(entry.sp_expire, entry[7])
        self.assertIsInstance(entry.sp_flag, int)
        self.assertEqual(entry.sp_flag, entry[8])
        with self.assertRaises(KeyError) as cx:
            spwd.getspnam('invalid user name')
        self.assertEqual(str(cx.exception), "'getspnam(): name not found'")
        self.assertRaises(TypeError, spwd.getspnam)
        self.assertRaises(TypeError, spwd.getspnam, 0)
        self.assertRaises(TypeError, spwd.getspnam, random_name, 0)

            

Reported by Pylint.

Missing class docstring
Error

Line: 62 Column: 1

              
@unittest.skipUnless(hasattr(os, 'geteuid') and os.geteuid() != 0,
                     'non-root user required')
class TestSpwdNonRoot(unittest.TestCase):

    def test_getspnam_exception(self):
        name = 'bin'
        try:
            with self.assertRaises(PermissionError) as cm:

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 64 Column: 5

                                   'non-root user required')
class TestSpwdNonRoot(unittest.TestCase):

    def test_getspnam_exception(self):
        name = 'bin'
        try:
            with self.assertRaises(PermissionError) as cm:
                spwd.getspnam(name)
        except KeyError as exc:

            

Reported by Pylint.

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

Line: 67 Column: 56

                  def test_getspnam_exception(self):
        name = 'bin'
        try:
            with self.assertRaises(PermissionError) as cm:
                spwd.getspnam(name)
        except KeyError as exc:
            self.skipTest("spwd entry %r doesn't exist: %s" % (name, exc))



            

Reported by Pylint.

Lib/test/test_setcomps.py
9 issues
Module 'sys' has no 'gettotalrefcount' member
Error

Line: 163 Column: 25

                      for i in range(len(counts)):
            support.run_doctest(test_setcomps, verbose)
            gc.collect()
            counts[i] = sys.gettotalrefcount()
        print(counts)

if __name__ == "__main__":
    test_main(verbose=True)

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              doctests = """
########### Tests mostly copied from test_listcomps.py ############

Test simple loop with conditional

    >>> sum({i*i for i in range(100) if i&1 == 1})
    166650

Test simple case

            

Reported by Pylint.

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

Line: 1 Column: 1

              doctests = """
########### Tests mostly copied from test_listcomps.py ############

Test simple loop with conditional

    >>> sum({i*i for i in range(100) if i&1 == 1})
    166650

Test simple case

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 150 Column: 1

              
__test__ = {'doctests' : doctests}

def test_main(verbose=None):
    import sys
    from test import support
    from test import test_setcomps
    support.run_doctest(test_setcomps, verbose)


            

Reported by Pylint.

Import outside toplevel (sys)
Error

Line: 151 Column: 5

              __test__ = {'doctests' : doctests}

def test_main(verbose=None):
    import sys
    from test import support
    from test import test_setcomps
    support.run_doctest(test_setcomps, verbose)

    # verify reference counting

            

Reported by Pylint.

Import outside toplevel (test.support)
Error

Line: 152 Column: 5

              
def test_main(verbose=None):
    import sys
    from test import support
    from test import test_setcomps
    support.run_doctest(test_setcomps, verbose)

    # verify reference counting
    if verbose and hasattr(sys, "gettotalrefcount"):

            

Reported by Pylint.

Import outside toplevel (test.test_setcomps)
Error

Line: 153 Column: 5

              def test_main(verbose=None):
    import sys
    from test import support
    from test import test_setcomps
    support.run_doctest(test_setcomps, verbose)

    # verify reference counting
    if verbose and hasattr(sys, "gettotalrefcount"):
        import gc

            

Reported by Pylint.

Import outside toplevel (gc)
Error

Line: 158 Column: 9

              
    # verify reference counting
    if verbose and hasattr(sys, "gettotalrefcount"):
        import gc
        counts = [None] * 5
        for i in range(len(counts)):
            support.run_doctest(test_setcomps, verbose)
            gc.collect()
            counts[i] = sys.gettotalrefcount()

            

Reported by Pylint.

Consider using enumerate instead of iterating with range and len
Error

Line: 160 Column: 9

                  if verbose and hasattr(sys, "gettotalrefcount"):
        import gc
        counts = [None] * 5
        for i in range(len(counts)):
            support.run_doctest(test_setcomps, verbose)
            gc.collect()
            counts[i] = sys.gettotalrefcount()
        print(counts)


            

Reported by Pylint.

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

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

                  if verbose:
        reporthook = print
    zip_dir.mkdir(parents=True, exist_ok=True)
    filename, headers = urlretrieve(
        url,
        zip_dir / f'{commit_hash}.zip',
        reporthook=reporthook,
    )
    return filename

            

Reported by Bandit.

Unused variable 'headers'
Error

Line: 17 Column: 15

                  if verbose:
        reporthook = print
    zip_dir.mkdir(parents=True, exist_ok=True)
    filename, headers = urlretrieve(
        url,
        zip_dir / f'{commit_hash}.zip',
        reporthook=reporthook,
    )
    return filename

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              #!/usr/bin/env python3

import argparse
import os
import pathlib
import zipfile
from urllib.request import urlretrieve



            

Reported by Pylint.

Missing function or method docstring
Error

Line: 10 Column: 1

              from urllib.request import urlretrieve


def fetch_zip(commit_hash, zip_dir, *, org='python', binary=False, verbose):
    repo = f'cpython-{"bin" if binary else "source"}-deps'
    url = f'https://github.com/{org}/{repo}/archive/{commit_hash}.zip'
    reporthook = None
    if verbose:
        reporthook = print

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 25 Column: 1

                  return filename


def extract_zip(externals_dir, zip_path):
    with zipfile.ZipFile(os.fspath(zip_path)) as zf:
        zf.extractall(os.fspath(externals_dir))
        return externals_dir / zf.namelist()[0].split('/')[0]



            

Reported by Pylint.

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

Line: 26 Column: 50

              

def extract_zip(externals_dir, zip_path):
    with zipfile.ZipFile(os.fspath(zip_path)) as zf:
        zf.extractall(os.fspath(externals_dir))
        return externals_dir / zf.namelist()[0].split('/')[0]


def parse_args():

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 31 Column: 1

                      return externals_dir / zf.namelist()[0].split('/')[0]


def parse_args():
    p = argparse.ArgumentParser()
    p.add_argument('-v', '--verbose', action='store_true')
    p.add_argument('-b', '--binary', action='store_true',
                   help='Is the dependency in the binary repo?')
    p.add_argument('-O', '--organization',

            

Reported by Pylint.

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

Line: 32 Column: 5

              

def parse_args():
    p = argparse.ArgumentParser()
    p.add_argument('-v', '--verbose', action='store_true')
    p.add_argument('-b', '--binary', action='store_true',
                   help='Is the dependency in the binary repo?')
    p.add_argument('-O', '--organization',
                   help='Organization owning the deps repos', default='python')

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 46 Column: 1

                  return p.parse_args()


def main():
    args = parse_args()
    zip_path = fetch_zip(
        args.tag,
        args.externals_dir / 'zips',
        org=args.organization,

            

Reported by Pylint.

Objects/bytearrayobject.c
9 issues
memcpy - Does not check for buffer overflows when copying to destination
Security

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

                          return PyErr_NoMemory();
        }
        if (bytes != NULL && size > 0)
            memcpy(new->ob_bytes, bytes, size);
        new->ob_bytes[size] = '\0';  /* Trailing null byte */
    }
    Py_SET_SIZE(new, size);
    new->ob_alloc = alloc;
    new->ob_start = new->ob_bytes;

            

Reported by FlawFinder.

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

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

                          PyErr_NoMemory();
            return -1;
        }
        memcpy(sval, PyByteArray_AS_STRING(self),
               Py_MIN((size_t)requested_size, (size_t)Py_SIZE(self)));
        PyObject_Free(obj->ob_bytes);
    }
    else {
        sval = PyObject_Realloc(obj->ob_bytes, alloc);

            

Reported by FlawFinder.

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

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

                  // result->ob_bytes is NULL if result is an empty bytearray:
    // if va.len + vb.len equals zero.
    if (result != NULL && result->ob_bytes != NULL) {
        memcpy(result->ob_bytes, va.buf, va.len);
        memcpy(result->ob_bytes + va.len, vb.buf, vb.len);
    }

  done:
    if (va.len != -1)

            

Reported by FlawFinder.

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

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

                  // if va.len + vb.len equals zero.
    if (result != NULL && result->ob_bytes != NULL) {
        memcpy(result->ob_bytes, va.buf, va.len);
        memcpy(result->ob_bytes + va.len, vb.buf, vb.len);
    }

  done:
    if (va.len != -1)
        PyBuffer_Release(&va);

            

Reported by FlawFinder.

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

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

                      PyBuffer_Release(&vo);
        return NULL;
    }
    memcpy(PyByteArray_AS_STRING(self) + size, vo.buf, vo.len);
    PyBuffer_Release(&vo);
    Py_INCREF(self);
    return (PyObject *)self;
}


            

Reported by FlawFinder.

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

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

                      else {
            Py_ssize_t i;
            for (i = 0; i < count; i++)
                memcpy(result->ob_bytes + i*mysize, buf, mysize);
        }
    }
    return (PyObject *)result;
}


            

Reported by FlawFinder.

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

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

                  else {
        Py_ssize_t i;
        for (i = 1; i < count; i++)
            memcpy(buf + i*mysize, buf, mysize);
    }

    Py_INCREF(self);
    return (PyObject *)self;
}

            

Reported by FlawFinder.

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

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

                  }

    if (bytes_len > 0)
        memcpy(buf + lo, bytes, bytes_len);
    return res;
}

static int
bytearray_setslice(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi,

            

Reported by FlawFinder.

strlen - Does not handle strings that are not \0-terminated; if given one it may perform an over-read (it could cause a crash if unprotected)
Security

Line: 923 Column: 15 CWE codes: 126

                  char *test, *start;
    char *buffer;

    newsize = strlen(className);
    if (length > (PY_SSIZE_T_MAX - 6 - newsize) / 4) {
        PyErr_SetString(PyExc_OverflowError,
            "bytearray object is too large to make repr");
        return NULL;
    }

            

Reported by FlawFinder.

Modules/_blake2/blake2b2s.py
9 issues
Missing module docstring
Error

Line: 1 Column: 1

              #!/usr/bin/python3

import os
import re

HERE = os.path.dirname(os.path.abspath(__file__))
BLAKE2 = os.path.join(HERE, 'impl')

PUBLIC_SEARCH = re.compile(r'\ int (blake2[bs]p?[a-z_]*)\(')

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 12 Column: 1

              PUBLIC_SEARCH = re.compile(r'\ int (blake2[bs]p?[a-z_]*)\(')


def getfiles():
    for name in os.listdir(BLAKE2):
        name = os.path.join(BLAKE2, name)
        if os.path.isfile(name):
            yield name


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 19 Column: 1

                          yield name


def find_public():
    public_funcs = set()
    for name in getfiles():
        with open(name) as f:
            for line in f:
                # find public functions

            

Reported by Pylint.

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

Line: 22 Column: 28

              def find_public():
    public_funcs = set()
    for name in getfiles():
        with open(name) as f:
            for line in f:
                # find public functions
                mo = PUBLIC_SEARCH.search(line)
                if mo:
                    public_funcs.add(mo.group(1))

            

Reported by Pylint.

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

Line: 25 Column: 17

                      with open(name) as f:
            for line in f:
                # find public functions
                mo = PUBLIC_SEARCH.search(line)
                if mo:
                    public_funcs.add(mo.group(1))

    for f in sorted(public_funcs):
        print('#define {0:<18} PyBlake2_{0}'.format(f))

            

Reported by Pylint.

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

Line: 29 Column: 9

                              if mo:
                    public_funcs.add(mo.group(1))

    for f in sorted(public_funcs):
        print('#define {0:<18} PyBlake2_{0}'.format(f))

    return public_funcs



            

Reported by Pylint.

Missing function or method docstring
Error

Line: 35 Column: 1

                  return public_funcs


def main():
    lines = []
    with open(os.path.join(HERE, 'blake2b_impl.c')) as f:
        for line in f:
            line = line.replace('blake2b', 'blake2s')
            line = line.replace('BLAKE2b', 'BLAKE2s')

            

Reported by Pylint.

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

Line: 37 Column: 56

              
def main():
    lines = []
    with open(os.path.join(HERE, 'blake2b_impl.c')) as f:
        for line in f:
            line = line.replace('blake2b', 'blake2s')
            line = line.replace('BLAKE2b', 'BLAKE2s')
            line = line.replace('BLAKE2B', 'BLAKE2S')
            lines.append(line)

            

Reported by Pylint.

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

Line: 43 Column: 61

                          line = line.replace('BLAKE2b', 'BLAKE2s')
            line = line.replace('BLAKE2B', 'BLAKE2S')
            lines.append(line)
    with open(os.path.join(HERE, 'blake2s_impl.c'), 'w') as f:
        f.write(''.join(lines))
    # find_public()


if __name__ == '__main__':

            

Reported by Pylint.

Lib/urllib/error.py
9 issues
__init__ method from base class 'OSError' is not called
Error

Line: 25 Column: 5

                  # It sets self.args for compatibility with other OSError
    # subclasses, but args doesn't have the typical format with errno in
    # slot 0 and strerror in slot 1.  This may be better than nothing.
    def __init__(self, reason, filename=None):
        self.args = reason,
        self.reason = reason
        if filename is not None:
            self.filename = filename


            

Reported by Pylint.

__init__ method from base class 'addinfourl' is not called
Error

Line: 39 Column: 5

                  """Raised when HTTP error occurs, but also acts like non-error return"""
    __super_init = urllib.response.addinfourl.__init__

    def __init__(self, url, code, msg, hdrs, fp):
        self.code = code
        self.msg = msg
        self.hdrs = hdrs
        self.fp = fp
        self.filename = url

            

Reported by Pylint.

__init__ method from base class 'URLError' is not called
Error

Line: 39 Column: 5

                  """Raised when HTTP error occurs, but also acts like non-error return"""
    __super_init = urllib.response.addinfourl.__init__

    def __init__(self, url, code, msg, hdrs, fp):
        self.code = code
        self.msg = msg
        self.hdrs = hdrs
        self.fp = fp
        self.filename = url

            

Reported by Pylint.

Missing class docstring
Error

Line: 19 Column: 1

              __all__ = ['URLError', 'HTTPError', 'ContentTooShortError']


class URLError(OSError):
    # URLError is a sub-type of OSError, but it doesn't share any of
    # the implementation.  need to override __init__ and __str__.
    # It sets self.args for compatibility with other OSError
    # subclasses, but args doesn't have the typical format with errno in
    # slot 0 and strerror in slot 1.  This may be better than nothing.

            

Reported by Pylint.

Disallow trailing comma tuple
Error

Line: 26 Column: 1

                  # subclasses, but args doesn't have the typical format with errno in
    # slot 0 and strerror in slot 1.  This may be better than nothing.
    def __init__(self, reason, filename=None):
        self.args = reason,
        self.reason = reason
        if filename is not None:
            self.filename = filename

    def __str__(self):

            

Reported by Pylint.

Too many ancestors (9/7)
Error

Line: 35 Column: 1

                      return '<urlopen error %s>' % self.reason


class HTTPError(URLError, urllib.response.addinfourl):
    """Raised when HTTP error occurs, but also acts like non-error return"""
    __super_init = urllib.response.addinfourl.__init__

    def __init__(self, url, code, msg, hdrs, fp):
        self.code = code

            

Reported by Pylint.

Too many arguments (6/5)
Error

Line: 39 Column: 5

                  """Raised when HTTP error occurs, but also acts like non-error return"""
    __super_init = urllib.response.addinfourl.__init__

    def __init__(self, url, code, msg, hdrs, fp):
        self.code = code
        self.msg = msg
        self.hdrs = hdrs
        self.fp = fp
        self.filename = url

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 61 Column: 5

                  # since URLError specifies a .reason attribute, HTTPError should also
    #  provide this attribute. See issue13211 for discussion.
    @property
    def reason(self):
        return self.msg

    @property
    def headers(self):
        return self.hdrs

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 65 Column: 5

                      return self.msg

    @property
    def headers(self):
        return self.hdrs

    @headers.setter
    def headers(self, headers):
        self.hdrs = headers

            

Reported by Pylint.

Modules/_io/winconsoleio.c
9 issues
Uninitialized variable: bytes_size
Error

Line: 860 CWE codes: 908

                      bytes_size = 0;
    }

    bytes_size += _buflen(self);
    bytes = PyBytes_FromStringAndSize(NULL, bytes_size);
    rn = _copyfrombuf(self, PyBytes_AS_STRING(bytes), bytes_size);

    if (len) {
        Py_BEGIN_ALLOW_THREADS

            

Reported by Cppcheck.

Uninitialized variable: bytes_size
Error

Line: 867 CWE codes: 908

                  if (len) {
        Py_BEGIN_ALLOW_THREADS
        bytes_size = WideCharToMultiByte(CP_UTF8, 0, buf, len,
            &PyBytes_AS_STRING(bytes)[rn], bytes_size - rn, NULL, NULL);
        Py_END_ALLOW_THREADS

        if (!bytes_size) {
            DWORD err = GetLastError();
            PyMem_Free(buf);

            

Reported by Cppcheck.

access - This usually indicates a security flaw. If an attacker can change anything along the path between the call to access() and the file's actual use (e.g., by moving files), the attacker can exploit the race condition
Security

Line: 359 Column: 40 CWE codes: 362/367!
Suggestion: Set up the correct permissions (e.g., using setuid()) and try to open the file directly

                      handle = CreateFileW(name, GENERIC_READ | GENERIC_WRITE,
            FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
        if (handle == INVALID_HANDLE_VALUE)
            handle = CreateFileW(name, access,
                FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
        Py_END_ALLOW_THREADS

        if (handle == INVALID_HANDLE_VALUE) {
            PyErr_SetExcFromWindowsErrWithFilenameObject(PyExc_OSError, GetLastError(), nameobj);

            

Reported by FlawFinder.

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

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

                  }

    DWORD length;
    wchar_t name_buf[MAX_PATH], *pname_buf = name_buf;

    length = GetFullPathNameW(decoded_wstr, MAX_PATH, pname_buf, NULL);
    if (length > MAX_PATH) {
        pname_buf = PyMem_New(wchar_t, length);
        if (pname_buf)

            

Reported by FlawFinder.

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

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

                  unsigned int blksize;
    PyObject *weakreflist;
    PyObject *dict;
    char buf[SMALLBUF];
    wchar_t wbuf;
} winconsoleio;

PyTypeObject PyWindowsConsoleIO_Type;


            

Reported by FlawFinder.

MultiByteToWideChar - Requires maximum length in CHARACTERS, not bytes
Security

Line: 980 Column: 12 CWE codes: 120

                      len = (DWORD)b->len;

    Py_BEGIN_ALLOW_THREADS
    wlen = MultiByteToWideChar(CP_UTF8, 0, b->buf, len, NULL, 0);

    /* issue11395 there is an unspecified upper bound on how many bytes
       can be written at once. We cap at 32k - the caller will have to
       handle partial writes.
       Since we don't know how many input bytes are being ignored, we

            

Reported by FlawFinder.

MultiByteToWideChar - Requires maximum length in CHARACTERS, not bytes
Security

Line: 989 Column: 16 CWE codes: 120

                     have to reduce and recalculate. */
    while (wlen > 32766 / sizeof(wchar_t)) {
        len /= 2;
        wlen = MultiByteToWideChar(CP_UTF8, 0, b->buf, len, NULL, 0);
    }
    Py_END_ALLOW_THREADS

    if (!wlen)
        return PyErr_SetFromWindowsErr(0);

            

Reported by FlawFinder.

MultiByteToWideChar - Requires maximum length in CHARACTERS, not bytes
Security

Line: 999 Column: 12 CWE codes: 120

                  wbuf = (wchar_t*)PyMem_Malloc(wlen * sizeof(wchar_t));

    Py_BEGIN_ALLOW_THREADS
    wlen = MultiByteToWideChar(CP_UTF8, 0, b->buf, len, wbuf, wlen);
    if (wlen) {
        res = WriteConsoleW(handle, wbuf, wlen, &n, NULL);
        if (res && n < wlen) {
            /* Wrote fewer characters than expected, which means our
             * len value may be wrong. So recalculate it from the

            

Reported by FlawFinder.

MultiByteToWideChar - Requires maximum length in CHARACTERS, not bytes
Security

Line: 1011 Column: 24 CWE codes: 120

                          len = WideCharToMultiByte(CP_UTF8, 0, wbuf, n,
                NULL, 0, NULL, NULL);
            if (len) {
                wlen = MultiByteToWideChar(CP_UTF8, 0, b->buf, len,
                    NULL, 0);
                assert(wlen == len);
            }
        }
    } else

            

Reported by FlawFinder.