The following issues were found

Lib/lib2to3/tests/test_main.py
10 issues
Attribute 'py2_src_dir' defined outside __init__
Error

Line: 59 Column: 9

                  def setup_test_source_trees(self):
        """Setup a test source tree and output destination tree."""
        self.temp_dir = tempfile.mkdtemp()  # tearDown() cleans this up.
        self.py2_src_dir = os.path.join(self.temp_dir, "python2_project")
        self.py3_dest_dir = os.path.join(self.temp_dir, "python3_project")
        os.mkdir(self.py2_src_dir)
        os.mkdir(self.py3_dest_dir)
        # Turn it into a package with a few files.
        self.setup_files = []

            

Reported by Pylint.

Attribute 'py3_dest_dir' defined outside __init__
Error

Line: 60 Column: 9

                      """Setup a test source tree and output destination tree."""
        self.temp_dir = tempfile.mkdtemp()  # tearDown() cleans this up.
        self.py2_src_dir = os.path.join(self.temp_dir, "python2_project")
        self.py3_dest_dir = os.path.join(self.temp_dir, "python3_project")
        os.mkdir(self.py2_src_dir)
        os.mkdir(self.py3_dest_dir)
        # Turn it into a package with a few files.
        self.setup_files = []
        open(os.path.join(self.py2_src_dir, "__init__.py"), "w").close()

            

Reported by Pylint.

Attribute 'setup_files' defined outside __init__
Error

Line: 64 Column: 9

                      os.mkdir(self.py2_src_dir)
        os.mkdir(self.py3_dest_dir)
        # Turn it into a package with a few files.
        self.setup_files = []
        open(os.path.join(self.py2_src_dir, "__init__.py"), "w").close()
        self.setup_files.append("__init__.py")
        shutil.copy(PY2_TEST_MODULE, self.py2_src_dir)
        self.setup_files.append(os.path.basename(PY2_TEST_MODULE))
        self.trivial_py2_file = os.path.join(self.py2_src_dir, "trivial.py")

            

Reported by Pylint.

Attribute 'trivial_py2_file' defined outside __init__
Error

Line: 69 Column: 9

                      self.setup_files.append("__init__.py")
        shutil.copy(PY2_TEST_MODULE, self.py2_src_dir)
        self.setup_files.append(os.path.basename(PY2_TEST_MODULE))
        self.trivial_py2_file = os.path.join(self.py2_src_dir, "trivial.py")
        self.init_py2_file = os.path.join(self.py2_src_dir, "__init__.py")
        with open(self.trivial_py2_file, "w") as trivial:
            trivial.write("print 'I need a simple conversion.'")
        self.setup_files.append("trivial.py")


            

Reported by Pylint.

Attribute 'init_py2_file' defined outside __init__
Error

Line: 70 Column: 9

                      shutil.copy(PY2_TEST_MODULE, self.py2_src_dir)
        self.setup_files.append(os.path.basename(PY2_TEST_MODULE))
        self.trivial_py2_file = os.path.join(self.py2_src_dir, "trivial.py")
        self.init_py2_file = os.path.join(self.py2_src_dir, "__init__.py")
        with open(self.trivial_py2_file, "w") as trivial:
            trivial.write("print 'I need a simple conversion.'")
        self.setup_files.append("trivial.py")

    def test_filename_changing_on_output_single_dir(self):

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              # -*- coding: utf-8 -*-
import codecs
import io
import logging
import os
import re
import shutil
import sys
import tempfile

            

Reported by Pylint.

Missing class docstring
Error

Line: 19 Column: 1

              PY2_TEST_MODULE = os.path.join(TEST_DATA_DIR, "py2_test_grammar.py")


class TestMain(unittest.TestCase):

    def setUp(self):
        self.temp_dir = None  # tearDown() will rmtree this directory if set.

    def tearDown(self):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 30 Column: 5

                      if self.temp_dir:
            shutil.rmtree(self.temp_dir)

    def run_2to3_capture(self, args, in_capture, out_capture, err_capture):
        save_stdin = sys.stdin
        save_stdout = sys.stdout
        save_stderr = sys.stderr
        sys.stdin = in_capture
        sys.stdout = out_capture

            

Reported by Pylint.

Method could be a function
Error

Line: 30 Column: 5

                      if self.temp_dir:
            shutil.rmtree(self.temp_dir)

    def run_2to3_capture(self, args, in_capture, out_capture, err_capture):
        save_stdin = sys.stdin
        save_stdout = sys.stdout
        save_stderr = sys.stderr
        sys.stdin = in_capture
        sys.stdout = out_capture

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 44 Column: 5

                          sys.stdout = save_stdout
            sys.stderr = save_stderr

    def test_unencodable_diff(self):
        input_stream = io.StringIO("print 'nothing'\nprint u'über'\n")
        out = io.BytesIO()
        out_enc = codecs.getwriter("ascii")(out)
        err = io.StringIO()
        ret = self.run_2to3_capture(["-"], input_stream, out_enc, err)

            

Reported by Pylint.

Lib/test/test_zoneinfo/data/update_test_data.py
10 issues
Unable to import 'zoneinfo'
Error

Line: 22 Column: 1

              import textwrap
import typing

import zoneinfo

KEYS = [
    "Africa/Abidjan",
    "Africa/Casablanca",
    "America/Los_Angeles",

            

Reported by Pylint.

Else clause on loop without a break statement
Error

Line: 48 Column: 5

                  for path in map(pathlib.Path, zoneinfo.TZPATH):
        if (path / key).exists():
            return path
    else:
        raise OSError("Cannot find time zone data.")


def get_zoneinfo_metadata() -> typing.Dict[str, str]:
    path = get_zoneinfo_path()

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 52 Column: 1

                      raise OSError("Cannot find time zone data.")


def get_zoneinfo_metadata() -> typing.Dict[str, str]:
    path = get_zoneinfo_path()

    tzdata_zi = path / "tzdata.zi"
    if not tzdata_zi.exists():
        # tzdata.zi is necessary to get the version information

            

Reported by Pylint.

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

Line: 60 Column: 34

                      # tzdata.zi is necessary to get the version information
        raise OSError("Time zone data does not include tzdata.zi.")

    with open(tzdata_zi, "r") as f:
        version_line = next(f)

    _, version = version_line.strip().rsplit(" ", 1)

    if (

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 79 Column: 1

                  return {"version": version}


def get_zoneinfo(key: str) -> bytes:
    path = get_zoneinfo_path()

    with open(path / key, "rb") as f:
        return f.read()


            

Reported by Pylint.

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

Line: 82 Column: 36

              def get_zoneinfo(key: str) -> bytes:
    path = get_zoneinfo_path()

    with open(path / key, "rb") as f:
        return f.read()


def encode_compressed(data: bytes) -> typing.List[str]:
    compressed_zone = lzma.compress(data)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 86 Column: 1

                      return f.read()


def encode_compressed(data: bytes) -> typing.List[str]:
    compressed_zone = lzma.compress(data)
    raw = base64.b85encode(compressed_zone)

    raw_data_str = raw.decode("utf-8")


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 96 Column: 1

                  return data_str


def load_compressed_keys() -> typing.Dict[str, typing.List[str]]:
    output = {key: encode_compressed(get_zoneinfo(key)) for key in KEYS}

    return output



            

Reported by Pylint.

Missing function or method docstring
Error

Line: 102 Column: 1

                  return output


def update_test_data(fname: str = "zoneinfo_data.json") -> None:
    TEST_DATA_LOC.mkdir(exist_ok=True, parents=True)

    # Annotation required: https://github.com/python/mypy/issues/8772
    json_kwargs: typing.Dict[str, typing.Any] = dict(
        indent=2, sort_keys=True,

            

Reported by Pylint.

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

Line: 117 Column: 46

                      "data": compressed_keys,
    }

    with open(TEST_DATA_LOC / fname, "w") as f:
        json.dump(output, f, **json_kwargs)


if __name__ == "__main__":
    update_test_data()

            

Reported by Pylint.

Lib/xml/sax/_exceptions.py
10 issues
Unable to import 'java.lang'
Error

Line: 4 Column: 5

              """Different kinds of SAX Exceptions"""
import sys
if sys.platform[:4] == "java":
    from java.lang import Exception
del sys

# ===== SAXEXCEPTION =====

class SAXException(Exception):

            

Reported by Pylint.

Redefining built-in 'Exception'
Error

Line: 4 Column: 5

              """Different kinds of SAX Exceptions"""
import sys
if sys.platform[:4] == "java":
    from java.lang import Exception
del sys

# ===== SAXEXCEPTION =====

class SAXException(Exception):

            

Reported by Pylint.

Method name "getMessage" doesn't conform to snake_case naming style
Error

Line: 26 Column: 5

                      self._exception = exception
        Exception.__init__(self, msg)

    def getMessage(self):
        "Return a message for this exception."
        return self._msg

    def getException(self):
        "Return the embedded exception, or None if there was none."

            

Reported by Pylint.

Method name "getException" doesn't conform to snake_case naming style
Error

Line: 30 Column: 5

                      "Return a message for this exception."
        return self._msg

    def getException(self):
        "Return the embedded exception, or None if there was none."
        return self._exception

    def __str__(self):
        "Create a string representation of the exception."

            

Reported by Pylint.

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

Line: 38 Column: 5

                      "Create a string representation of the exception."
        return self._msg

    def __getitem__(self, ix):
        """Avoids weird error messages if someone does exception[ix] by
        mistake, since Exception has __getitem__ defined."""
        raise AttributeError("__getitem__")



            

Reported by Pylint.

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

Line: 68 Column: 9

                      # If this exception is raised, the objects through which we must
        # traverse to get this information may be deleted by the time
        # it gets caught.
        self._systemId = self._locator.getSystemId()
        self._colnum = self._locator.getColumnNumber()
        self._linenum = self._locator.getLineNumber()

    def getColumnNumber(self):
        """The column number of the end of the text where the exception

            

Reported by Pylint.

Method name "getColumnNumber" doesn't conform to snake_case naming style
Error

Line: 72 Column: 5

                      self._colnum = self._locator.getColumnNumber()
        self._linenum = self._locator.getLineNumber()

    def getColumnNumber(self):
        """The column number of the end of the text where the exception
        occurred."""
        return self._colnum

    def getLineNumber(self):

            

Reported by Pylint.

Method name "getLineNumber" doesn't conform to snake_case naming style
Error

Line: 77 Column: 5

                      occurred."""
        return self._colnum

    def getLineNumber(self):
        "The line number of the end of the text where the exception occurred."
        return self._linenum

    def getPublicId(self):
        "Get the public identifier of the entity where the exception occurred."

            

Reported by Pylint.

Method name "getPublicId" doesn't conform to snake_case naming style
Error

Line: 81 Column: 5

                      "The line number of the end of the text where the exception occurred."
        return self._linenum

    def getPublicId(self):
        "Get the public identifier of the entity where the exception occurred."
        return self._locator.getPublicId()

    def getSystemId(self):
        "Get the system identifier of the entity where the exception occurred."

            

Reported by Pylint.

Method name "getSystemId" doesn't conform to snake_case naming style
Error

Line: 85 Column: 5

                      "Get the public identifier of the entity where the exception occurred."
        return self._locator.getPublicId()

    def getSystemId(self):
        "Get the system identifier of the entity where the exception occurred."
        return self._systemId

    def __str__(self):
        "Create a string representation of the exception."

            

Reported by Pylint.

Lib/urllib/robotparser.py
10 issues
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 read(self):
        """Reads the robots.txt URL and feeds it to the parser."""
        try:
            f = urllib.request.urlopen(self.url)
        except urllib.error.HTTPError as err:
            if err.code in (401, 403):
                self.disallow_all = True
            elif err.code >= 400 and err.code < 500:
                self.allow_all = True

            

Reported by Bandit.

Too many instance attributes (9/7)
Error

Line: 22 Column: 1

              RequestRate = collections.namedtuple("RequestRate", "requests seconds")


class RobotFileParser:
    """ This class provides a set of methods to read, parse and answer
    questions about a single robots.txt file.

    """


            

Reported by Pylint.

Import outside toplevel (time)
Error

Line: 51 Column: 9

                      current time.

        """
        import time
        self.last_checked = time.time()

    def set_url(self, url):
        """Sets the URL referring to a robots.txt file."""
        self.url = url

            

Reported by Pylint.

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

Line: 62 Column: 13

                  def read(self):
        """Reads the robots.txt URL and feeds it to the parser."""
        try:
            f = urllib.request.urlopen(self.url)
        except urllib.error.HTTPError as err:
            if err.code in (401, 403):
                self.disallow_all = True
            elif err.code >= 400 and err.code < 500:
                self.allow_all = True

            

Reported by Pylint.

Too many statements (51/50)
Error

Line: 81 Column: 5

                      else:
            self.entries.append(entry)

    def parse(self, lines):
        """Parse the input lines from a robots.txt file.

        We allow that a user-agent: line is not preceded by
        one or more blank lines.
        """

            

Reported by Pylint.

Too many branches (21/12)
Error

Line: 81 Column: 5

                      else:
            self.entries.append(entry)

    def parse(self, lines):
        """Parse the input lines from a robots.txt file.

        We allow that a user-agent: line is not preceded by
        one or more blank lines.
        """

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 183 Column: 5

                      # agent not found ==> access granted
        return True

    def crawl_delay(self, useragent):
        if not self.mtime():
            return None
        for entry in self.entries:
            if entry.applies_to(useragent):
                return entry.delay

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 193 Column: 5

                          return self.default_entry.delay
        return None

    def request_rate(self, useragent):
        if not self.mtime():
            return None
        for entry in self.entries:
            if entry.applies_to(useragent):
                return entry.req_rate

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 203 Column: 5

                          return self.default_entry.req_rate
        return None

    def site_maps(self):
        if not self.sitemaps:
            return None
        return self.sitemaps

    def __str__(self):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 226 Column: 5

                      self.path = urllib.parse.quote(path)
        self.allowance = allowance

    def applies_to(self, filename):
        return self.path == "*" or filename.startswith(self.path)

    def __str__(self):
        return ("Allow" if self.allowance else "Disallow") + ": " + self.path


            

Reported by Pylint.

Lib/unittest/test/testmock/support.py
10 issues
Missing module docstring
Error

Line: 1 Column: 1

              target = {'foo': 'FOO'}


def is_instance(obj, klass):
    """Version of is_instance that doesn't access __class__"""
    return issubclass(type(obj), klass)


class SomeClass(object):

            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 9 Column: 1

                  return issubclass(type(obj), klass)


class SomeClass(object):
    class_attribute = None

    def wibble(self): pass



            

Reported by Pylint.

Missing class docstring
Error

Line: 9 Column: 1

                  return issubclass(type(obj), klass)


class SomeClass(object):
    class_attribute = None

    def wibble(self): pass



            

Reported by Pylint.

Class 'SomeClass' inherits from object, can be safely removed from bases in python3
Error

Line: 9 Column: 1

                  return issubclass(type(obj), klass)


class SomeClass(object):
    class_attribute = None

    def wibble(self): pass



            

Reported by Pylint.

Missing function or method docstring
Error

Line: 12 Column: 5

              class SomeClass(object):
    class_attribute = None

    def wibble(self): pass


class X(object):
    pass

            

Reported by Pylint.

More than one statement on a single line
Error

Line: 12 Column: 23

              class SomeClass(object):
    class_attribute = None

    def wibble(self): pass


class X(object):
    pass

            

Reported by Pylint.

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

Line: 15 Column: 1

                  def wibble(self): pass


class X(object):
    pass

            

Reported by Pylint.

Class 'X' inherits from object, can be safely removed from bases in python3
Error

Line: 15 Column: 1

                  def wibble(self): pass


class X(object):
    pass

            

Reported by Pylint.

Too few public methods (0/2)
Error

Line: 15 Column: 1

                  def wibble(self): pass


class X(object):
    pass

            

Reported by Pylint.

Missing class docstring
Error

Line: 15 Column: 1

                  def wibble(self): pass


class X(object):
    pass

            

Reported by Pylint.

Lib/test/test_ttk_guionly.py
10 issues
Unable to import '_tkinter'
Error

Line: 12 Column: 1

              support.requires('gui')

import tkinter
from _tkinter import TclError
from tkinter import ttk
from tkinter.test import runtktests

root = None
try:

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import unittest
from test import support
from test.support import import_helper

# Skip this test if _tkinter wasn't built.
import_helper.import_module('_tkinter')

# Skip test if tk cannot be initialized.
support.requires('gui')

            

Reported by Pylint.

Import "import tkinter" should be placed at the top of the module
Error

Line: 11 Column: 1

              # Skip test if tk cannot be initialized.
support.requires('gui')

import tkinter
from _tkinter import TclError
from tkinter import ttk
from tkinter.test import runtktests

root = None

            

Reported by Pylint.

Import "from _tkinter import TclError" should be placed at the top of the module
Error

Line: 12 Column: 1

              support.requires('gui')

import tkinter
from _tkinter import TclError
from tkinter import ttk
from tkinter.test import runtktests

root = None
try:

            

Reported by Pylint.

Import "from tkinter import ttk" should be placed at the top of the module
Error

Line: 13 Column: 1

              
import tkinter
from _tkinter import TclError
from tkinter import ttk
from tkinter.test import runtktests

root = None
try:
    root = tkinter.Tk()

            

Reported by Pylint.

standard import "from tkinter import ttk" should be placed before "from _tkinter import TclError"
Error

Line: 13 Column: 1

              
import tkinter
from _tkinter import TclError
from tkinter import ttk
from tkinter.test import runtktests

root = None
try:
    root = tkinter.Tk()

            

Reported by Pylint.

standard import "from tkinter.test import runtktests" should be placed before "from _tkinter import TclError"
Error

Line: 14 Column: 1

              import tkinter
from _tkinter import TclError
from tkinter import ttk
from tkinter.test import runtktests

root = None
try:
    root = tkinter.Tk()
    button = ttk.Button(root)

            

Reported by Pylint.

Import "from tkinter.test import runtktests" should be placed at the top of the module
Error

Line: 14 Column: 1

              import tkinter
from _tkinter import TclError
from tkinter import ttk
from tkinter.test import runtktests

root = None
try:
    root = tkinter.Tk()
    button = ttk.Button(root)

            

Reported by Pylint.

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

Line: 16 Column: 1

              from tkinter import ttk
from tkinter.test import runtktests

root = None
try:
    root = tkinter.Tk()
    button = ttk.Button(root)
    button.destroy()
    del button

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 30 Column: 1

                      root.destroy()
    del root

def test_main():
    support.run_unittest(
            *runtktests.get_tests(text=False, packages=['test_ttk']))

if __name__ == '__main__':
    test_main()

            

Reported by Pylint.

Lib/test/test_peg_generator/test_grammar_validator.py
10 issues
Unable to import 'pegen.grammar_parser'
Error

Line: 6 Column: 5

              
test_tools.skip_if_missing("peg_generator")
with test_tools.imports_under_tool("peg_generator"):
    from pegen.grammar_parser import GeneratedParser as GrammarParser
    from pegen.validator import SubRuleValidator, ValidationError
    from pegen.testutil import parse_string
    from pegen.grammar import Grammar



            

Reported by Pylint.

Unable to import 'pegen.validator'
Error

Line: 7 Column: 5

              test_tools.skip_if_missing("peg_generator")
with test_tools.imports_under_tool("peg_generator"):
    from pegen.grammar_parser import GeneratedParser as GrammarParser
    from pegen.validator import SubRuleValidator, ValidationError
    from pegen.testutil import parse_string
    from pegen.grammar import Grammar


class TestPegen(unittest.TestCase):

            

Reported by Pylint.

Unable to import 'pegen.testutil'
Error

Line: 8 Column: 5

              with test_tools.imports_under_tool("peg_generator"):
    from pegen.grammar_parser import GeneratedParser as GrammarParser
    from pegen.validator import SubRuleValidator, ValidationError
    from pegen.testutil import parse_string
    from pegen.grammar import Grammar


class TestPegen(unittest.TestCase):
    def test_rule_with_no_collision(self) -> None:

            

Reported by Pylint.

Unable to import 'pegen.grammar'
Error

Line: 9 Column: 5

                  from pegen.grammar_parser import GeneratedParser as GrammarParser
    from pegen.validator import SubRuleValidator, ValidationError
    from pegen.testutil import parse_string
    from pegen.grammar import Grammar


class TestPegen(unittest.TestCase):
    def test_rule_with_no_collision(self) -> None:
        grammar_source = """

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import unittest
from test import test_tools

test_tools.skip_if_missing("peg_generator")
with test_tools.imports_under_tool("peg_generator"):
    from pegen.grammar_parser import GeneratedParser as GrammarParser
    from pegen.validator import SubRuleValidator, ValidationError
    from pegen.testutil import parse_string
    from pegen.grammar import Grammar

            

Reported by Pylint.

Missing class docstring
Error

Line: 12 Column: 1

                  from pegen.grammar import Grammar


class TestPegen(unittest.TestCase):
    def test_rule_with_no_collision(self) -> None:
        grammar_source = """
        start: bad_rule
        sum:
            | NAME '-' NAME

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 13 Column: 5

              

class TestPegen(unittest.TestCase):
    def test_rule_with_no_collision(self) -> None:
        grammar_source = """
        start: bad_rule
        sum:
            | NAME '-' NAME
            | NAME '+' NAME

            

Reported by Pylint.

Method could be a function
Error

Line: 13 Column: 5

              

class TestPegen(unittest.TestCase):
    def test_rule_with_no_collision(self) -> None:
        grammar_source = """
        start: bad_rule
        sum:
            | NAME '-' NAME
            | NAME '+' NAME

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 25 Column: 5

                      for rule_name, rule in grammar.rules.items():
            validator.validate_rule(rule_name, rule)

    def test_rule_with_simple_collision(self) -> None:
        grammar_source = """
        start: bad_rule
        sum:
            | NAME '+' NAME
            | NAME '+' NAME ';'

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 38 Column: 5

                          for rule_name, rule in grammar.rules.items():
                validator.validate_rule(rule_name, rule)

    def test_rule_with_collision_after_some_other_rules(self) -> None:
        grammar_source = """
        start: bad_rule
        sum:
            | NAME '+' NAME
            | NAME '*' NAME ';'

            

Reported by Pylint.

Lib/test/test_unicode_file.py
10 issues
Chmod setting a permissive mask 0o777 on file (filename).
Security

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

                      self.assertTrue(os.path.exists(os.path.abspath(filename)))
        self.assertTrue(os.path.isfile(os.path.abspath(filename)))
        self.assertTrue(os.access(os.path.abspath(filename), os.R_OK))
        os.chmod(filename, 0o777)
        os.utime(filename, None)
        os.utime(filename, (time.time(), time.time()))
        # Copy/rename etc tests using the same filename
        self._do_copyish(filename, filename)
        # Filename should appear in glob output

            

Reported by Bandit.

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

Line: 20 Column: 9

                  except (UnicodeError, TypeError):
        # Either the file system encoding is None, or the file name
        # cannot be encoded in the file system encoding.
        raise unittest.SkipTest("No Unicode filesystem semantics on this platform.")

def remove_if_exists(filename):
    if os.path.exists(filename):
        os.unlink(filename)


            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              # Test some Unicode file name semantics
# We don't test many operations on files other than
# that their names can be used with Unicode characters.
import os, glob, time, shutil
import sys
import unicodedata

import unittest
from test.support import run_unittest

            

Reported by Pylint.

Multiple imports on one line (os, glob, time, shutil)
Error

Line: 4 Column: 1

              # Test some Unicode file name semantics
# We don't test many operations on files other than
# that their names can be used with Unicode characters.
import os, glob, time, shutil
import sys
import unicodedata

import unittest
from test.support import run_unittest

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 22 Column: 1

                      # cannot be encoded in the file system encoding.
        raise unittest.SkipTest("No Unicode filesystem semantics on this platform.")

def remove_if_exists(filename):
    if os.path.exists(filename):
        os.unlink(filename)

class TestUnicodeFiles(unittest.TestCase):
    # The 'do_' functions are the actual tests.  They generally assume the

            

Reported by Pylint.

Missing class docstring
Error

Line: 26 Column: 1

                  if os.path.exists(filename):
        os.unlink(filename)

class TestUnicodeFiles(unittest.TestCase):
    # The 'do_' functions are the actual tests.  They generally assume the
    # file already exists etc.

    # Do all the tests we can given only a single filename.  The file should
    # exist.

            

Reported by Pylint.

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

Line: 114 Column: 9

                          os.unlink(filename)
        self.assertTrue(not os.path.exists(filename))
        # and again with os.open.
        f = os.open(filename, os.O_CREAT)
        os.close(f)
        try:
            self._do_single(filename)
        finally:
            os.unlink(filename)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 123 Column: 5

              
    # The 'test' functions are unittest entry points, and simply call our
    # _test functions with each of the filename combinations we wish to test
    def test_single_files(self):
        self._test_single(TESTFN_UNICODE)
        if TESTFN_UNENCODABLE is not None:
            self._test_single(TESTFN_UNENCODABLE)

    def test_directories(self):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 128 Column: 5

                      if TESTFN_UNENCODABLE is not None:
            self._test_single(TESTFN_UNENCODABLE)

    def test_directories(self):
        # For all 'equivalent' combinations:
        #  Make dir with encoded, chdir with unicode, checkdir with encoded
        #  (or unicode/encoded/unicode, etc
        ext = ".dir"
        self._do_directory(TESTFN_UNICODE+ext, TESTFN_UNICODE+ext)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 139 Column: 1

                          self._do_directory(TESTFN_UNENCODABLE+ext,
                               TESTFN_UNENCODABLE+ext)

def test_main():
    run_unittest(__name__)

if __name__ == "__main__":
    test_main()

            

Reported by Pylint.

Tools/c-analyzer/c_parser/preprocessor/gcc.py
10 issues
Attempted relative import beyond top-level package
Error

Line: 4 Column: 1

              import os.path
import re

from . import common as _common


TOOL = 'gcc'

# https://gcc.gnu.org/onlinedocs/cpp/Preprocessor-Output.html

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import os.path
import re

from . import common as _common


TOOL = 'gcc'

# https://gcc.gnu.org/onlinedocs/cpp/Preprocessor-Output.html

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 43 Column: 1

              )


def preprocess(filename, incldirs=None, macros=None, samefiles=None):
    text = _common.preprocess(
        TOOL,
        filename,
        incldirs=incldirs,
        macros=macros,

            

Reported by Pylint.

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

Line: 64 Column: 9

                  partial = 0  # depth
    origfile = None
    for line in lines:
        m = LINE_MARKER_RE.match(line)
        if m:
            lno, origfile = m.groups()
            lno = int(lno)
        elif _filter_orig_file(origfile, filename, samefiles):
            if (m := PREPROC_DIRECTIVE_RE.match(line)):

            

Reported by Pylint.

Unnecessary parens after 'if' keyword
Error

Line: 69 Column: 1

                          lno, origfile = m.groups()
            lno = int(lno)
        elif _filter_orig_file(origfile, filename, samefiles):
            if (m := PREPROC_DIRECTIVE_RE.match(line)):
                name, = m.groups()
                if name != 'pragma':
                    raise Exception(line)
            else:
                if not raw:

            

Reported by Pylint.

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

Line: 69 Column: 17

                          lno, origfile = m.groups()
            lno = int(lno)
        elif _filter_orig_file(origfile, filename, samefiles):
            if (m := PREPROC_DIRECTIVE_RE.match(line)):
                name, = m.groups()
                if name != 'pragma':
                    raise Exception(line)
            else:
                if not raw:

            

Reported by Pylint.

Unnecessary parens after 'not' keyword
Error

Line: 88 Column: 1

              def _strip_directives(line, partial=0):
    # We assume there are no string literals with parens in directive bodies.
    while partial > 0:
        if not (m := re.match(r'[^{}]*([()])', line)):
            return None, partial
        delim, = m.groups()
        partial += 1 if delim == '(' else -1  # opened/closed
        line = line[m.end():]


            

Reported by Pylint.

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

Line: 88 Column: 17

              def _strip_directives(line, partial=0):
    # We assume there are no string literals with parens in directive bodies.
    while partial > 0:
        if not (m := re.match(r'[^{}]*([()])', line)):
            return None, partial
        delim, = m.groups()
        partial += 1 if delim == '(' else -1  # opened/closed
        line = line[m.end():]


            

Reported by Pylint.

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

Line: 96 Column: 12

              
    line = re.sub(r'__extension__', '', line)

    while (m := COMPILER_DIRECTIVE_RE.match(line)):
        before, _, _, closed = m.groups()
        if closed:
            line = f'{before} {line[m.end():]}'
        else:
            after, partial = _strip_directives(line[m.end():], 2)

            

Reported by Pylint.

Unnecessary parens after 'while' keyword
Error

Line: 96 Column: 1

              
    line = re.sub(r'__extension__', '', line)

    while (m := COMPILER_DIRECTIVE_RE.match(line)):
        before, _, _, closed = m.groups()
        if closed:
            line = f'{before} {line[m.end():]}'
        else:
            after, partial = _strip_directives(line[m.end():], 2)

            

Reported by Pylint.

Tools/c-analyzer/c_common/logging.py
10 issues
Module 'logging' has no 'getLogger' member
Error

Line: 9 Column: 11

              

# The root logger for the whole top-level package:
_logger = logging.getLogger(__name__.rpartition('.')[0])


def configure_logger(logger, verbosity=VERBOSITY, *,
                     logfile=None,
                     maxlevel=logging.CRITICAL,

            

Reported by Pylint.

Module 'logging' has no 'CRITICAL' member
Error

Line: 14 Column: 31

              
def configure_logger(logger, verbosity=VERBOSITY, *,
                     logfile=None,
                     maxlevel=logging.CRITICAL,
                     ):
    level = max(1,  # 0 disables it, so we use the next lowest.
                min(maxlevel,
                    maxlevel - verbosity * 10))
    logger.setLevel(level)

            

Reported by Pylint.

Module 'logging' has no 'FileHandler' member
Error

Line: 24 Column: 23

              
    if not logger.handlers:
        if logfile:
            handler = logging.FileHandler(logfile)
        else:
            handler = logging.StreamHandler(sys.stdout)
        handler.setLevel(level)
        #handler.setFormatter(logging.Formatter())
        logger.addHandler(handler)

            

Reported by Pylint.

Module 'logging' has no 'StreamHandler' member
Error

Line: 26 Column: 23

                      if logfile:
            handler = logging.FileHandler(logfile)
        else:
            handler = logging.StreamHandler(sys.stdout)
        handler.setLevel(level)
        #handler.setFormatter(logging.Formatter())
        logger.addHandler(handler)

    # In case the provided logger is in a sub-package...

            

Reported by Pylint.

Module import itself
Error

Line: 1 Column: 1

              import logging
import sys


VERBOSITY = 3


# The root logger for the whole top-level package:
_logger = logging.getLogger(__name__.rpartition('.')[0])

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import logging
import sys


VERBOSITY = 3


# The root logger for the whole top-level package:
_logger = logging.getLogger(__name__.rpartition('.')[0])

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 12 Column: 1

              _logger = logging.getLogger(__name__.rpartition('.')[0])


def configure_logger(logger, verbosity=VERBOSITY, *,
                     logfile=None,
                     maxlevel=logging.CRITICAL,
                     ):
    level = max(1,  # 0 disables it, so we use the next lowest.
                min(maxlevel,

            

Reported by Pylint.

Missing class docstring
Error

Line: 56 Column: 1

                  return restore


class Printer:
    def __init__(self, verbosity=VERBOSITY):
        self.verbosity = verbosity

    def info(self, *args, **kwargs):
        if self.verbosity < 3:

            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 56 Column: 1

                  return restore


class Printer:
    def __init__(self, verbosity=VERBOSITY):
        self.verbosity = verbosity

    def info(self, *args, **kwargs):
        if self.verbosity < 3:

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 60 Column: 5

                  def __init__(self, verbosity=VERBOSITY):
        self.verbosity = verbosity

    def info(self, *args, **kwargs):
        if self.verbosity < 3:
            return
        print(*args, **kwargs)

            

Reported by Pylint.