The following issues were found

Tools/tz/zdump.py
19 issues
Redefining name 'fileobj' from outer scope (line 79)
Error

Line: 18 Column: 23

                      self.abbrs = abbrs

    @classmethod
    def fromfile(cls, fileobj):
        if fileobj.read(4).decode() != "TZif":
            raise ValueError("not a zoneinfo file")
        fileobj.seek(20)
        header = fileobj.read(24)
        tzh = (tzh_ttisgmtcnt, tzh_ttisstdcnt, tzh_leapcnt,

            

Reported by Pylint.

Unused variable 'tzh_leapcnt'
Error

Line: 23 Column: 48

                          raise ValueError("not a zoneinfo file")
        fileobj.seek(20)
        header = fileobj.read(24)
        tzh = (tzh_ttisgmtcnt, tzh_ttisstdcnt, tzh_leapcnt,
               tzh_timecnt, tzh_typecnt, tzh_charcnt) = struct.unpack(">6l", header)
        transitions = array('i')
        transitions.fromfile(fileobj, tzh_timecnt)
        if sys.byteorder != 'big':
            transitions.byteswap()

            

Reported by Pylint.

Unused variable 'tzh_ttisstdcnt'
Error

Line: 23 Column: 32

                          raise ValueError("not a zoneinfo file")
        fileobj.seek(20)
        header = fileobj.read(24)
        tzh = (tzh_ttisgmtcnt, tzh_ttisstdcnt, tzh_leapcnt,
               tzh_timecnt, tzh_typecnt, tzh_charcnt) = struct.unpack(">6l", header)
        transitions = array('i')
        transitions.fromfile(fileobj, tzh_timecnt)
        if sys.byteorder != 'big':
            transitions.byteswap()

            

Reported by Pylint.

Unused variable 'tzh_ttisgmtcnt'
Error

Line: 23 Column: 16

                          raise ValueError("not a zoneinfo file")
        fileobj.seek(20)
        header = fileobj.read(24)
        tzh = (tzh_ttisgmtcnt, tzh_ttisstdcnt, tzh_leapcnt,
               tzh_timecnt, tzh_typecnt, tzh_charcnt) = struct.unpack(">6l", header)
        transitions = array('i')
        transitions.fromfile(fileobj, tzh_timecnt)
        if sys.byteorder != 'big':
            transitions.byteswap()

            

Reported by Pylint.

Unused variable 'i'
Error

Line: 34 Column: 13

                      type_indices.fromfile(fileobj, tzh_timecnt)

        ttis = []
        for i in range(tzh_typecnt):
            ttis.append(ttinfo._make(struct.unpack(">lbb", fileobj.read(6))))

        abbrs = fileobj.read(tzh_charcnt)

        self = cls(transitions, type_indices, ttis, abbrs)

            

Reported by Pylint.

Attribute 'tzh' defined outside __init__
Error

Line: 40 Column: 9

                      abbrs = fileobj.read(tzh_charcnt)

        self = cls(transitions, type_indices, ttis, abbrs)
        self.tzh = tzh

        return self

    def dump(self, stream, start=None, end=None):
        for j, (trans, i) in enumerate(zip(self.transitions, self.type_indices)):

            

Reported by Pylint.

Unused argument 'start'
Error

Line: 44 Column: 28

              
        return self

    def dump(self, stream, start=None, end=None):
        for j, (trans, i) in enumerate(zip(self.transitions, self.type_indices)):
            utc = datetime.utcfromtimestamp(trans)
            tti = self.ttis[i]
            lmt = datetime.utcfromtimestamp(trans + tti.tt_gmtoff)
            abbrind = tti.tt_abbrind

            

Reported by Pylint.

Unused argument 'end'
Error

Line: 44 Column: 40

              
        return self

    def dump(self, stream, start=None, end=None):
        for j, (trans, i) in enumerate(zip(self.transitions, self.type_indices)):
            utc = datetime.utcfromtimestamp(trans)
            tti = self.ttis[i]
            lmt = datetime.utcfromtimestamp(trans + tti.tt_gmtoff)
            abbrind = tti.tt_abbrind

            

Reported by Pylint.

Redefining name 'zones' from outer scope (line 72)
Error

Line: 60 Column: 9

              
    @classmethod
    def zonelist(cls, zonedir='/usr/share/zoneinfo'):
        zones = []
        for root, _, files in os.walk(zonedir):
            for f in files:
                p = os.path.join(root, f)
                with open(p, 'rb') as o:
                    magic =  o.read(4)

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import sys
import os
import struct
from array import array
from collections import namedtuple
from datetime import datetime

ttinfo = namedtuple('ttinfo', ['tt_gmtoff', 'tt_isdst', 'tt_abbrind'])


            

Reported by Pylint.

Tools/peg_generator/scripts/test_parse_directory.py
19 issues
Unused import traceback
Error

Line: 8 Column: 1

              import os
import sys
import time
import traceback
import tokenize
from glob import glob, escape
from pathlib import PurePath

from typing import List, Optional, Any, Tuple

            

Reported by Pylint.

Unused ast_dump imported from pegen.ast_dump
Error

Line: 16 Column: 1

              from typing import List, Optional, Any, Tuple

sys.path.insert(0, os.getcwd())
from pegen.ast_dump import ast_dump
from pegen.testutil import print_memstats

SUCCESS = "\033[92m"
FAIL = "\033[91m"
ENDC = "\033[0m"

            

Reported by Pylint.

Using an f-string that does not have any interpolated variables
Error

Line: 112 Column: 61

                  files = []
    total_seconds = 0

    for file in sorted(glob(os.path.join(escape(directory), f"**/*.py"), recursive=True)):
        # Only attempt to parse Python files and files that are not excluded
        if any(PurePath(file).match(pattern) for pattern in excluded_files):
            continue

        with tokenize.open(file) as f:

            

Reported by Pylint.

Unused variable 'result'
Error

Line: 121 Column: 13

                          source = f.read()

        try:
            result, dt = parse_file(source, file)
            total_seconds += dt
            report_status(succeeded=True, file=file, verbose=verbose, short=short)
        except SyntaxError as error:
            report_status(succeeded=False, file=file, verbose=verbose, error=error, short=short)
            errors += 1

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              #!/usr/bin/env python3.8

import argparse
import ast
import os
import sys
import time
import traceback
import tokenize

            

Reported by Pylint.

Import "from pegen.ast_dump import ast_dump" should be placed at the top of the module
Error

Line: 16 Column: 1

              from typing import List, Optional, Any, Tuple

sys.path.insert(0, os.getcwd())
from pegen.ast_dump import ast_dump
from pegen.testutil import print_memstats

SUCCESS = "\033[92m"
FAIL = "\033[91m"
ENDC = "\033[0m"

            

Reported by Pylint.

Import "from pegen.testutil import print_memstats" should be placed at the top of the module
Error

Line: 17 Column: 1

              
sys.path.insert(0, os.getcwd())
from pegen.ast_dump import ast_dump
from pegen.testutil import print_memstats

SUCCESS = "\033[92m"
FAIL = "\033[91m"
ENDC = "\033[0m"


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 43 Column: 1

              )


def report_status(
    succeeded: bool,
    file: str,
    verbose: bool,
    error: Optional[Exception] = None,
    short: bool = False,

            

Reported by Pylint.

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

Line: 55 Column: 9

              
    if succeeded is True:
        status = "OK"
        COLOR = SUCCESS
    else:
        status = "Fail"
        COLOR = FAIL

    if short:

            

Reported by Pylint.

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

Line: 58 Column: 9

                      COLOR = SUCCESS
    else:
        status = "Fail"
        COLOR = FAIL

    if short:
        lineno = 0
        offset = 0
        if isinstance(error, SyntaxError):

            

Reported by Pylint.

Tools/scripts/byext.py
18 issues
Redefining built-in 'dir'
Error

Line: 24 Column: 23

                              sys.stderr.write("Can't find %s\n" % arg)
                self.addstats("<???>", "unknown", 1)

    def statdir(self, dir):
        self.addstats("<dir>", "dirs", 1)
        try:
            names = os.listdir(dir)
        except OSError as err:
            sys.stderr.write("Can't list %s: %s\n" % (dir, err))

            

Reported by Pylint.

Unused variable 'head'
Error

Line: 46 Column: 9

                              self.statfile(full)

    def statfile(self, filename):
        head, ext = os.path.splitext(filename)
        head, base = os.path.split(filename)
        if ext == base:
            ext = ""  # E.g. .cvsignore is deemed not to have an extension
        ext = os.path.normcase(ext)
        if not ext:

            

Reported by Pylint.

Missing class docstring
Error

Line: 9 Column: 1

              import sys


class Stats:

    def __init__(self):
        self.stats = {}

    def statargs(self, args):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 14 Column: 5

                  def __init__(self):
        self.stats = {}

    def statargs(self, args):
        for arg in args:
            if os.path.isdir(arg):
                self.statdir(arg)
            elif os.path.isfile(arg):
                self.statfile(arg)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 24 Column: 5

                              sys.stderr.write("Can't find %s\n" % arg)
                self.addstats("<???>", "unknown", 1)

    def statdir(self, dir):
        self.addstats("<dir>", "dirs", 1)
        try:
            names = os.listdir(dir)
        except OSError as err:
            sys.stderr.write("Can't list %s: %s\n" % (dir, err))

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 45 Column: 5

                          else:
                self.statfile(full)

    def statfile(self, filename):
        head, ext = os.path.splitext(filename)
        head, base = os.path.split(filename)
        if ext == base:
            ext = ""  # E.g. .cvsignore is deemed not to have an extension
        ext = os.path.normcase(ext)

            

Reported by Pylint.

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

Line: 55 Column: 42

                          ext = "<none>"
        self.addstats(ext, "files", 1)
        try:
            with open(filename, "rb") as f:
                data = f.read()
        except IOError as err:
            sys.stderr.write("Can't open %s: %s\n" % (filename, err))
            self.addstats(ext, "unopenable", 1)
            return

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 74 Column: 5

                      words = data.split()
        self.addstats(ext, "words", len(words))

    def addstats(self, ext, key, n):
        d = self.stats.setdefault(ext, {})
        d[key] = d.get(key, 0) + n

    def report(self):
        exts = sorted(self.stats)

            

Reported by Pylint.

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

Line: 74 Column: 5

                      words = data.split()
        self.addstats(ext, "words", len(words))

    def addstats(self, ext, key, n):
        d = self.stats.setdefault(ext, {})
        d[key] = d.get(key, 0) + n

    def report(self):
        exts = sorted(self.stats)

            

Reported by Pylint.

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

Line: 75 Column: 9

                      self.addstats(ext, "words", len(words))

    def addstats(self, ext, key, n):
        d = self.stats.setdefault(ext, {})
        d[key] = d.get(key, 0) + n

    def report(self):
        exts = sorted(self.stats)
        # Get the column keys

            

Reported by Pylint.

Lib/tkinter/font.py
18 issues
Redefining name 'root' from outer scope (line 206)
Error

Line: 20 Column: 22

              ITALIC = "italic"


def nametofont(name, root=None):
    """Given the name of a tk named font, returns a Font representation.
    """
    return Font(name=name, exists=True, root=root)



            

Reported by Pylint.

Redefining name 'root' from outer scope (line 206)
Error

Line: 69 Column: 24

                          options[args[i][1:]] = args[i+1]
        return options

    def __init__(self, root=None, font=None, name=None, exists=False,
                 **options):
        if root is None:
            root = tkinter._get_default_root('use font')
        tk = getattr(root, 'tk', root)
        if font:

            

Reported by Pylint.

Catching too general exception Exception
Error

Line: 122 Column: 16

                      try:
            if self.delete_font:
                self._call("font", "delete", self.name)
        except Exception:
            pass

    def copy(self):
        "Return a distinct copy of the current font"
        return Font(self._tk, **self.actual())

            

Reported by Pylint.

Redefining name 'root' from outer scope (line 206)
Error

Line: 184 Column: 14

                          return options


def families(root=None, displayof=None):
    "Get font families (as a tuple)"
    if root is None:
        root = tkinter._get_default_root('use font.families()')
    args = ()
    if displayof:

            

Reported by Pylint.

Access to a protected member _get_default_root of a client class
Error

Line: 187 Column: 16

              def families(root=None, displayof=None):
    "Get font families (as a tuple)"
    if root is None:
        root = tkinter._get_default_root('use font.families()')
    args = ()
    if displayof:
        args = ('-displayof', displayof)
    return root.tk.splitlist(root.tk.call("font", "families", *args))


            

Reported by Pylint.

Redefining name 'root' from outer scope (line 206)
Error

Line: 194 Column: 11

                  return root.tk.splitlist(root.tk.call("font", "families", *args))


def names(root=None):
    "Get names of defined fonts (as a tuple)"
    if root is None:
        root = tkinter._get_default_root('use font.names()')
    return root.tk.splitlist(root.tk.call("font", "names"))


            

Reported by Pylint.

Access to a protected member _get_default_root of a client class
Error

Line: 197 Column: 16

              def names(root=None):
    "Get names of defined fonts (as a tuple)"
    if root is None:
        root = tkinter._get_default_root('use font.names()')
    return root.tk.splitlist(root.tk.call("font", "names"))


# --------------------------------------------------------------------
# test stuff

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              # Tkinter font wrapper
#
# written by Fredrik Lundh, February 1998
#

import itertools
import tkinter

__version__ = "0.9"

            

Reported by Pylint.

Method could be a function
Error

Line: 50 Column: 5

              
    counter = itertools.count(1)

    def _set(self, kw):
        options = []
        for k, v in kw.items():
            options.append("-"+k)
            options.append(str(v))
        return tuple(options)

            

Reported by Pylint.

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

Line: 50 Column: 5

              
    counter = itertools.count(1)

    def _set(self, kw):
        options = []
        for k, v in kw.items():
            options.append("-"+k)
            options.append(str(v))
        return tuple(options)

            

Reported by Pylint.

Lib/test/test_pickletools.py
18 issues
Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.
Security blacklist

Line: 13
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b301-pickle

                      return pickletools.optimize(pickle.dumps(arg, proto, **kwargs))

    def loads(self, buf, **kwds):
        return pickle.loads(buf, **kwds)

    # Test relies on precise output of dumps()
    test_pickle_to_2x = None

    # Test relies on writing by chunks into a file object.

            

Reported by Bandit.

Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.
Security blacklist

Line: 26
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b301-pickle

                      data.append(data[-1])
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            pickled = pickle.dumps(data, proto)
            unpickled = pickle.loads(pickled)
            self.assertEqual(unpickled, data)
            self.assertIs(unpickled[-1], unpickled[-2])

            pickled2 = pickletools.optimize(pickled)
            unpickled2 = pickle.loads(pickled2)

            

Reported by Bandit.

Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.
Security blacklist

Line: 31
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b301-pickle

                          self.assertIs(unpickled[-1], unpickled[-2])

            pickled2 = pickletools.optimize(pickled)
            unpickled2 = pickle.loads(pickled2)
            self.assertEqual(unpickled2, data)
            self.assertIs(unpickled2[-1], unpickled2[-2])
            self.assertNotIn(pickle.LONG_BINGET, pickled2)
            self.assertNotIn(pickle.LONG_BINPUT, pickled2)


            

Reported by Bandit.

Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.
Security blacklist

Line: 53
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b301-pickle

                      #   30: e        APPENDS    (MARK at 13)
        #   31: .    STOP
        self.assertIn(pickle.BINPUT, pickled)
        unpickled = pickle.loads(pickled)
        self.assertEqual(unpickled, ['spam', 'ham', 'ham'])
        self.assertIs(unpickled[1], unpickled[2])

        pickled2 = pickletools.optimize(pickled)
        unpickled2 = pickle.loads(pickled2)

            

Reported by Bandit.

Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.
Security blacklist

Line: 58
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b301-pickle

                      self.assertIs(unpickled[1], unpickled[2])

        pickled2 = pickletools.optimize(pickled)
        unpickled2 = pickle.loads(pickled2)
        self.assertEqual(unpickled2, ['spam', 'ham', 'ham'])
        self.assertIs(unpickled2[1], unpickled2[2])
        self.assertNotIn(pickle.BINPUT, pickled2)



            

Reported by Bandit.

Consider possible security implications associated with pickle module.
Security blacklist

Line: 1
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_imports.html#b403-import-pickle

              import pickle
import pickletools
from test import support
from test.pickletester import AbstractPickleTests
import unittest

class OptimizedPickleTests(AbstractPickleTests):

    def dumps(self, arg, proto=None, **kwargs):

            

Reported by Bandit.

Missing module docstring
Error

Line: 1 Column: 1

              import pickle
import pickletools
from test import support
from test.pickletester import AbstractPickleTests
import unittest

class OptimizedPickleTests(AbstractPickleTests):

    def dumps(self, arg, proto=None, **kwargs):

            

Reported by Pylint.

Consider possible security implications associated with pickletools module.
Security blacklist

Line: 2
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_imports.html#b403-import-pickle

              import pickle
import pickletools
from test import support
from test.pickletester import AbstractPickleTests
import unittest

class OptimizedPickleTests(AbstractPickleTests):

    def dumps(self, arg, proto=None, **kwargs):

            

Reported by Bandit.

Missing class docstring
Error

Line: 7 Column: 1

              from test.pickletester import AbstractPickleTests
import unittest

class OptimizedPickleTests(AbstractPickleTests):

    def dumps(self, arg, proto=None, **kwargs):
        return pickletools.optimize(pickle.dumps(arg, proto, **kwargs))

    def loads(self, buf, **kwds):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 9 Column: 5

              
class OptimizedPickleTests(AbstractPickleTests):

    def dumps(self, arg, proto=None, **kwargs):
        return pickletools.optimize(pickle.dumps(arg, proto, **kwargs))

    def loads(self, buf, **kwds):
        return pickle.loads(buf, **kwds)


            

Reported by Pylint.

Lib/unittest/util.py
18 issues
Catching too general exception Exception
Error

Line: 48 Column: 12

              def safe_repr(obj, short=False):
    try:
        result = repr(obj)
    except Exception:
        result = object.__repr__(obj)
    if not short or len(result) < _MAX_LENGTH:
        return result
    return result[:_MAX_LENGTH] + ' [truncated]...'


            

Reported by Pylint.

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

Line: 6 Column: 1

              from collections import namedtuple, Counter
from os.path import commonprefix

__unittest = True

_MAX_LENGTH = 80
_PLACEHOLDER_LEN = 12
_MIN_BEGIN_LEN = 5
_MIN_END_LEN = 5

            

Reported by Pylint.

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

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

              _MIN_DIFF_LEN = _MAX_LENGTH - \
               (_MIN_BEGIN_LEN + _PLACEHOLDER_LEN + _MIN_COMMON_LEN +
                _PLACEHOLDER_LEN + _MIN_END_LEN)
assert _MIN_DIFF_LEN >= 0

def _shorten(s, prefixlen, suffixlen):
    skip = len(s) - prefixlen - suffixlen
    if skip > _PLACEHOLDER_LEN:
        s = '%s[%d chars]%s' % (s[:prefixlen], skip, s[len(s) - suffixlen:])

            

Reported by Bandit.

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

Line: 18 Column: 1

                              _PLACEHOLDER_LEN + _MIN_END_LEN)
assert _MIN_DIFF_LEN >= 0

def _shorten(s, prefixlen, suffixlen):
    skip = len(s) - prefixlen - suffixlen
    if skip > _PLACEHOLDER_LEN:
        s = '%s[%d chars]%s' % (s[:prefixlen], skip, s[len(s) - suffixlen:])
    return s


            

Reported by Pylint.

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

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

                  common_len = _MAX_LENGTH - \
                 (maxlen - prefixlen + _MIN_BEGIN_LEN + _PLACEHOLDER_LEN)
    if common_len > _MIN_COMMON_LEN:
        assert _MIN_BEGIN_LEN + _PLACEHOLDER_LEN + _MIN_COMMON_LEN + \
               (maxlen - prefixlen) < _MAX_LENGTH
        prefix = _shorten(prefix, _MIN_BEGIN_LEN, common_len)
        return tuple(prefix + s[prefixlen:] for s in args)

    prefix = _shorten(prefix, _MIN_BEGIN_LEN, _MIN_COMMON_LEN)

            

Reported by Bandit.

Missing function or method docstring
Error

Line: 45 Column: 1

                  return tuple(prefix + _shorten(s[prefixlen:], _MIN_DIFF_LEN, _MIN_END_LEN)
                 for s in args)

def safe_repr(obj, short=False):
    try:
        result = repr(obj)
    except Exception:
        result = object.__repr__(obj)
    if not short or len(result) < _MAX_LENGTH:

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 54 Column: 1

                      return result
    return result[:_MAX_LENGTH] + ' [truncated]...'

def strclass(cls):
    return "%s.%s" % (cls.__module__, cls.__qualname__)

def sorted_list_difference(expected, actual):
    """Finds elements in only one or the other of two, sorted input lists.


            

Reported by Pylint.

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

Line: 70 Column: 13

                  unexpected = []
    while True:
        try:
            e = expected[i]
            a = actual[j]
            if e < a:
                missing.append(e)
                i += 1
                while expected[i] == e:

            

Reported by Pylint.

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

Line: 71 Column: 13

                  while True:
        try:
            e = expected[i]
            a = actual[j]
            if e < a:
                missing.append(e)
                i += 1
                while expected[i] == e:
                    i += 1

            

Reported by Pylint.

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

Line: 115 Column: 1

                  # anything left in actual is unexpected
    return missing, actual

def three_way_cmp(x, y):
    """Return -1 if x < y, 0 if x == y and 1 if x > y"""
    return (x > y) - (x < y)

_Mismatch = namedtuple('Mismatch', 'actual expected value')


            

Reported by Pylint.

Lib/test/test_script_helper.py
18 issues
Unused variable 'out'
Error

Line: 19 Column: 13

              
    def test_assert_python_failure(self):
        # I didn't import the sys module so this child will fail.
        rc, out, err = script_helper.assert_python_failure('-c', 'sys.exit(0)')
        self.assertNotEqual(0, rc, 'return code should not be 0')

    def test_assert_python_ok_raises(self):
        # I didn't import the sys module so this child will fail.
        with self.assertRaises(AssertionError) as error_context:

            

Reported by Pylint.

Unused variable 'err'
Error

Line: 19 Column: 18

              
    def test_assert_python_failure(self):
        # I didn't import the sys module so this child will fail.
        rc, out, err = script_helper.assert_python_failure('-c', 'sys.exit(0)')
        self.assertNotEqual(0, rc, 'return code should not be 0')

    def test_assert_python_ok_raises(self):
        # I didn't import the sys module so this child will fail.
        with self.assertRaises(AssertionError) as error_context:

            

Reported by Pylint.

Access to a protected member _assert_python of a client class
Error

Line: 45 Column: 17

                                             return_value=False) as mock_ire_func:
            mock_popen.side_effect = RuntimeError('bail out of unittest')
            try:
                script_helper._assert_python(True, '-c', 'None')
            except RuntimeError as err:
                self.assertEqual('bail out of unittest', err.args[0])
            self.assertEqual(1, mock_popen.call_count)
            self.assertEqual(1, mock_ire_func.call_count)
            popen_command = mock_popen.call_args[0][0]

            

Reported by Pylint.

Unused variable 'mock_ire_func'
Error

Line: 61 Column: 54

                      """Ensure that -I is not passed when the environment is required."""
        with mock.patch.object(script_helper,
                               'interpreter_requires_environment',
                               return_value=True) as mock_ire_func:
            mock_popen.side_effect = RuntimeError('bail out of unittest')
            try:
                script_helper._assert_python(True, '-c', 'None')
            except RuntimeError as err:
                self.assertEqual('bail out of unittest', err.args[0])

            

Reported by Pylint.

Access to a protected member _assert_python of a client class
Error

Line: 64 Column: 17

                                             return_value=True) as mock_ire_func:
            mock_popen.side_effect = RuntimeError('bail out of unittest')
            try:
                script_helper._assert_python(True, '-c', 'None')
            except RuntimeError as err:
                self.assertEqual('bail out of unittest', err.args[0])
            popen_command = mock_popen.call_args[0][0]
            self.assertNotIn('-I', popen_command)
            self.assertNotIn('-E', popen_command)

            

Reported by Pylint.

Consider possible security implications associated with subprocess module.
Security blacklist

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

              """Unittests for test.support.script_helper.  Who tests the test helper?"""

import subprocess
import sys
import os
from test.support import script_helper
import unittest
from unittest import mock


            

Reported by Bandit.

Missing class docstring
Error

Line: 11 Column: 1

              from unittest import mock


class TestScriptHelper(unittest.TestCase):

    def test_assert_python_ok(self):
        t = script_helper.assert_python_ok('-c', 'import sys; sys.exit(0)')
        self.assertEqual(0, t[0], 'return code was not 0')


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 13 Column: 5

              
class TestScriptHelper(unittest.TestCase):

    def test_assert_python_ok(self):
        t = script_helper.assert_python_ok('-c', 'import sys; sys.exit(0)')
        self.assertEqual(0, t[0], 'return code was not 0')

    def test_assert_python_failure(self):
        # I didn't import the sys module so this child will fail.

            

Reported by Pylint.

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

Line: 14 Column: 9

              class TestScriptHelper(unittest.TestCase):

    def test_assert_python_ok(self):
        t = script_helper.assert_python_ok('-c', 'import sys; sys.exit(0)')
        self.assertEqual(0, t[0], 'return code was not 0')

    def test_assert_python_failure(self):
        # I didn't import the sys module so this child will fail.
        rc, out, err = script_helper.assert_python_failure('-c', 'sys.exit(0)')

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 17 Column: 5

                      t = script_helper.assert_python_ok('-c', 'import sys; sys.exit(0)')
        self.assertEqual(0, t[0], 'return code was not 0')

    def test_assert_python_failure(self):
        # I didn't import the sys module so this child will fail.
        rc, out, err = script_helper.assert_python_failure('-c', 'sys.exit(0)')
        self.assertNotEqual(0, rc, 'return code should not be 0')

    def test_assert_python_ok_raises(self):

            

Reported by Pylint.

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

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

                      return NULL;
    }

    memcpy(str2, str, size);
    return str2;
}

char *
_PyMem_RawStrdup(const char *str)

            

Reported by FlawFinder.

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

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

                  if (copy == NULL) {
        return NULL;
    }
    memcpy(copy, str, size);
    return copy;
}

char *
_PyMem_Strdup(const char *str)

            

Reported by FlawFinder.

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

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

                  if (copy == NULL) {
        return NULL;
    }
    memcpy(copy, str, size);
    return copy;
}

void *
PyObject_Malloc(size_t size)

            

Reported by FlawFinder.

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

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

              
    bp = _PyObject_Malloc(ctx, nbytes);
    if (bp != NULL) {
        memcpy(bp, p, size);
        _PyObject_Free(ctx, p);
    }
    *newptr_p = bp;
    return 1;
}

            

Reported by FlawFinder.

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

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

                     ERASED_SIZE bytes at the end as dead and save the copy of erased bytes.
     */
    if (original_nbytes <= sizeof(save)) {
        memcpy(save, data, original_nbytes);
        memset(data - 2 * SST, PYMEM_DEADBYTE,
               original_nbytes + PYMEM_DEBUG_EXTRA_BYTES);
    }
    else {
        memcpy(save, data, ERASED_SIZE);

            

Reported by FlawFinder.

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

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

                             original_nbytes + PYMEM_DEBUG_EXTRA_BYTES);
    }
    else {
        memcpy(save, data, ERASED_SIZE);
        memset(head, PYMEM_DEADBYTE, ERASED_SIZE + 2 * SST);
        memcpy(&save[ERASED_SIZE], tail - ERASED_SIZE, ERASED_SIZE);
        memset(tail - ERASED_SIZE, PYMEM_DEADBYTE,
               ERASED_SIZE + PYMEM_DEBUG_EXTRA_BYTES - 2 * SST);
    }

            

Reported by FlawFinder.

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

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

                  else {
        memcpy(save, data, ERASED_SIZE);
        memset(head, PYMEM_DEADBYTE, ERASED_SIZE + 2 * SST);
        memcpy(&save[ERASED_SIZE], tail - ERASED_SIZE, ERASED_SIZE);
        memset(tail - ERASED_SIZE, PYMEM_DEADBYTE,
               ERASED_SIZE + PYMEM_DEBUG_EXTRA_BYTES - 2 * SST);
    }

    /* Resize and add decorations. */

            

Reported by FlawFinder.

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

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

              
    /* Restore saved bytes. */
    if (original_nbytes <= sizeof(save)) {
        memcpy(data, save, Py_MIN(nbytes, original_nbytes));
    }
    else {
        size_t i = original_nbytes - ERASED_SIZE;
        memcpy(data, save, Py_MIN(nbytes, ERASED_SIZE));
        if (nbytes > i) {

            

Reported by FlawFinder.

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

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

                  }
    else {
        size_t i = original_nbytes - ERASED_SIZE;
        memcpy(data, save, Py_MIN(nbytes, ERASED_SIZE));
        if (nbytes > i) {
            memcpy(data + i, &save[ERASED_SIZE],
                   Py_MIN(nbytes - i, ERASED_SIZE));
        }
    }

            

Reported by FlawFinder.

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

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

                      size_t i = original_nbytes - ERASED_SIZE;
        memcpy(data, save, Py_MIN(nbytes, ERASED_SIZE));
        if (nbytes > i) {
            memcpy(data + i, &save[ERASED_SIZE],
                   Py_MIN(nbytes - i, ERASED_SIZE));
        }
    }

    if (r == NULL) {

            

Reported by FlawFinder.

Lib/urllib/response.py
18 issues
Access to a protected member _TemporaryFileWrapper of a client class
Error

Line: 14 Column: 15

              __all__ = ['addbase', 'addclosehook', 'addinfo', 'addinfourl']


class addbase(tempfile._TemporaryFileWrapper):
    """Base class for addinfo and addclosehook. Is a good idea for garbage collection."""

    # XXX Add a method to expose the timeout on the underlying socket?

    def __init__(self, fp):

            

Reported by Pylint.

XXX Add a method to expose the timeout on the underlying socket?
Error

Line: 17 Column: 3

              class addbase(tempfile._TemporaryFileWrapper):
    """Base class for addinfo and addclosehook. Is a good idea for garbage collection."""

    # XXX Add a method to expose the timeout on the underlying socket?

    def __init__(self, fp):
        super(addbase,  self).__init__(fp, '<urllib response>', delete=False)
        # Keep reference around as this was part of the original API.
        self.fp = fp

            

Reported by Pylint.

Redefining built-in 'type'
Error

Line: 33 Column: 24

                          raise ValueError("I/O operation on closed file")
        return self

    def __exit__(self, type, value, traceback):
        self.close()


class addclosehook(addbase):
    """Class to add a close hook to an open file."""

            

Reported by Pylint.

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

Line: 14 Column: 1

              __all__ = ['addbase', 'addclosehook', 'addinfo', 'addinfourl']


class addbase(tempfile._TemporaryFileWrapper):
    """Base class for addinfo and addclosehook. Is a good idea for garbage collection."""

    # XXX Add a method to expose the timeout on the underlying socket?

    def __init__(self, fp):

            

Reported by Pylint.

Consider using Python 3 style super() without arguments
Error

Line: 20 Column: 9

                  # XXX Add a method to expose the timeout on the underlying socket?

    def __init__(self, fp):
        super(addbase,  self).__init__(fp, '<urllib response>', delete=False)
        # Keep reference around as this was part of the original API.
        self.fp = fp

    def __repr__(self):
        return '<%s at %r whose fp = %r>' % (self.__class__.__name__,

            

Reported by Pylint.

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

Line: 22 Column: 9

                  def __init__(self, fp):
        super(addbase,  self).__init__(fp, '<urllib response>', delete=False)
        # Keep reference around as this was part of the original API.
        self.fp = fp

    def __repr__(self):
        return '<%s at %r whose fp = %r>' % (self.__class__.__name__,
                                             id(self), self.file)


            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 37 Column: 1

                      self.close()


class addclosehook(addbase):
    """Class to add a close hook to an open file."""

    def __init__(self, fp, closehook, *hookargs):
        super(addclosehook, self).__init__(fp)
        self.closehook = closehook

            

Reported by Pylint.

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

Line: 37 Column: 1

                      self.close()


class addclosehook(addbase):
    """Class to add a close hook to an open file."""

    def __init__(self, fp, closehook, *hookargs):
        super(addclosehook, self).__init__(fp)
        self.closehook = closehook

            

Reported by Pylint.

Consider using Python 3 style super() without arguments
Error

Line: 41 Column: 9

                  """Class to add a close hook to an open file."""

    def __init__(self, fp, closehook, *hookargs):
        super(addclosehook, self).__init__(fp)
        self.closehook = closehook
        self.hookargs = hookargs

    def close(self):
        try:

            

Reported by Pylint.

Consider using Python 3 style super() without arguments
Error

Line: 54 Column: 13

                              self.hookargs = None
                closehook(*hookargs)
        finally:
            super(addclosehook, self).close()


class addinfo(addbase):
    """class to add an info() method to an open file."""


            

Reported by Pylint.

Lib/zoneinfo/_common.py
18 issues
Instance of '_TZifHeader' has no 'version' member
Error

Line: 30 Column: 8

              def load_data(fobj):
    header = _TZifHeader.from_file(fobj)

    if header.version == 1:
        time_size = 4
        time_type = "l"
    else:
        # Version 2+ has 64-bit integer transition times
        time_size = 8

            

Reported by Pylint.

Instance of '_TZifHeader' has no 'timecnt' member
Error

Line: 41 Column: 13

                      # Version 2+ also starts with a Version 1 header and data, which
        # we need to skip now
        skip_bytes = (
            header.timecnt * 5  # Transition times and types
            + header.typecnt * 6  # Local time type records
            + header.charcnt  # Time zone designations
            + header.leapcnt * 8  # Leap second records
            + header.isstdcnt  # Standard/wall indicators
            + header.isutcnt  # UT/local indicators

            

Reported by Pylint.

Instance of '_TZifHeader' has no 'typecnt' member
Error

Line: 42 Column: 15

                      # we need to skip now
        skip_bytes = (
            header.timecnt * 5  # Transition times and types
            + header.typecnt * 6  # Local time type records
            + header.charcnt  # Time zone designations
            + header.leapcnt * 8  # Leap second records
            + header.isstdcnt  # Standard/wall indicators
            + header.isutcnt  # UT/local indicators
        )

            

Reported by Pylint.

Instance of '_TZifHeader' has no 'charcnt' member
Error

Line: 43 Column: 15

                      skip_bytes = (
            header.timecnt * 5  # Transition times and types
            + header.typecnt * 6  # Local time type records
            + header.charcnt  # Time zone designations
            + header.leapcnt * 8  # Leap second records
            + header.isstdcnt  # Standard/wall indicators
            + header.isutcnt  # UT/local indicators
        )


            

Reported by Pylint.

Instance of '_TZifHeader' has no 'leapcnt' member
Error

Line: 44 Column: 15

                          header.timecnt * 5  # Transition times and types
            + header.typecnt * 6  # Local time type records
            + header.charcnt  # Time zone designations
            + header.leapcnt * 8  # Leap second records
            + header.isstdcnt  # Standard/wall indicators
            + header.isutcnt  # UT/local indicators
        )

        fobj.seek(skip_bytes, 1)

            

Reported by Pylint.

Instance of '_TZifHeader' has no 'isstdcnt' member
Error

Line: 45 Column: 15

                          + header.typecnt * 6  # Local time type records
            + header.charcnt  # Time zone designations
            + header.leapcnt * 8  # Leap second records
            + header.isstdcnt  # Standard/wall indicators
            + header.isutcnt  # UT/local indicators
        )

        fobj.seek(skip_bytes, 1)


            

Reported by Pylint.

Instance of '_TZifHeader' has no 'isutcnt' member
Error

Line: 46 Column: 15

                          + header.charcnt  # Time zone designations
            + header.leapcnt * 8  # Leap second records
            + header.isstdcnt  # Standard/wall indicators
            + header.isutcnt  # UT/local indicators
        )

        fobj.seek(skip_bytes, 1)

        # Now we need to read the second header, which is not the same

            

Reported by Pylint.

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

Line: 24 Column: 9

                      #   (e.g. Europe/Krasnoy)
        # UnicodeEncodeError: If package_name or resource_name are not UTF-8,
        #   such as keys containing a surrogate character.
        raise ZoneInfoNotFoundError(f"No time zone found with key {key}")


def load_data(fobj):
    header = _TZifHeader.from_file(fobj)


            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import struct


def load_tzdata(key):
    import importlib.resources

    components = key.split("/")
    package_name = ".".join(["tzdata.zoneinfo"] + components[:-1])
    resource_name = components[-1]

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 4 Column: 1

              import struct


def load_tzdata(key):
    import importlib.resources

    components = key.split("/")
    package_name = ".".join(["tzdata.zoneinfo"] + components[:-1])
    resource_name = components[-1]

            

Reported by Pylint.