The following issues were found

Tools/pynche/TextViewer.py
46 issues
Unable to import 'tkinter'
Error

Line: 18 Column: 1

              in the text window (which only has a background).
"""

from tkinter import *
import ColorDB

ADDTOVIEW = 'Text Window...'



            

Reported by Pylint.

Unable to import 'ColorDB'
Error

Line: 19 Column: 1

              """

from tkinter import *
import ColorDB

ADDTOVIEW = 'Text Window...'




            

Reported by Pylint.

Undefined variable 'Toplevel'
Error

Line: 29 Column: 30

                  def __init__(self, switchboard, master=None):
        self.__sb = switchboard
        optiondb = switchboard.optiondb()
        root = self.__root = Toplevel(master, class_='Pynche')
        root.protocol('WM_DELETE_WINDOW', self.withdraw)
        root.title('Pynche Text Window')
        root.iconname('Pynche Text Window')
        root.bind('<Alt-q>', self.__quit)
        root.bind('<Alt-Q>', self.__quit)

            

Reported by Pylint.

Undefined variable 'SUNKEN'
Error

Line: 40 Column: 41

                      #
        # create the text widget
        #
        self.__text = Text(root, relief=SUNKEN,
                           background=optiondb.get('TEXTBG', 'black'),
                           foreground=optiondb.get('TEXTFG', 'white'),
                           width=35, height=15)
        sfg = optiondb.get('TEXT_SFG')
        if sfg:

            

Reported by Pylint.

Undefined variable 'Text'
Error

Line: 40 Column: 23

                      #
        # create the text widget
        #
        self.__text = Text(root, relief=SUNKEN,
                           background=optiondb.get('TEXTBG', 'black'),
                           foreground=optiondb.get('TEXTFG', 'white'),
                           width=35, height=15)
        sfg = optiondb.get('TEXT_SFG')
        if sfg:

            

Reported by Pylint.

Undefined variable 'INSERT'
Error

Line: 65 Column: 34

              and choosing a color.'''))
        insert = optiondb.get('TEXTINS')
        if insert:
            self.__text.mark_set(INSERT, insert)
        try:
            start, end = optiondb.get('TEXTSEL', (6.0, END))
            self.__text.tag_add(SEL, start, end)
        except ValueError:
            # selection wasn't set

            

Reported by Pylint.

Undefined variable 'END'
Error

Line: 67 Column: 56

                      if insert:
            self.__text.mark_set(INSERT, insert)
        try:
            start, end = optiondb.get('TEXTSEL', (6.0, END))
            self.__text.tag_add(SEL, start, end)
        except ValueError:
            # selection wasn't set
            pass
        self.__text.focus_set()

            

Reported by Pylint.

Undefined variable 'SEL'
Error

Line: 68 Column: 33

                          self.__text.mark_set(INSERT, insert)
        try:
            start, end = optiondb.get('TEXTSEL', (6.0, END))
            self.__text.tag_add(SEL, start, end)
        except ValueError:
            # selection wasn't set
            pass
        self.__text.focus_set()
        #

            

Reported by Pylint.

Undefined variable 'BooleanVar'
Error

Line: 75 Column: 25

                      self.__text.focus_set()
        #
        # variables
        self.__trackp = BooleanVar()
        self.__trackp.set(optiondb.get('TRACKP', 0))
        self.__which = IntVar()
        self.__which.set(optiondb.get('WHICH', 0))
        #
        # track toggle

            

Reported by Pylint.

Undefined variable 'IntVar'
Error

Line: 77 Column: 24

                      # variables
        self.__trackp = BooleanVar()
        self.__trackp.set(optiondb.get('TRACKP', 0))
        self.__which = IntVar()
        self.__which.set(optiondb.get('WHICH', 0))
        #
        # track toggle
        self.__t = Checkbutton(root, text='Track color changes',
                               variable=self.__trackp,

            

Reported by Pylint.

Tools/unicode/gencodec.py
45 issues
No value for argument 'dir' in function call
Error

Line: 424 Column: 9

              
    import sys
    if 1:
        convertdir(*sys.argv[1:])
    else:
        rewritepythondir(*sys.argv[1:])

            

Reported by Pylint.

No value for argument 'dir' in function call
Error

Line: 426 Column: 9

                  if 1:
        convertdir(*sys.argv[1:])
    else:
        rewritepythondir(*sys.argv[1:])

            

Reported by Pylint.

Redefining built-in 'len'
Error

Line: 46 Column: 23

                                 r'\s*'
                   r'(#.+)?')

def parsecodes(codes, len=len, range=range):

    """ Converts code combinations to either a single code integer
        or a tuple of integers.

        meta-codes (in angular brackets, e.g. <LR> and <RL>) are

            

Reported by Pylint.

Redefining built-in 'range'
Error

Line: 46 Column: 32

                                 r'\s*'
                   r'(#.+)?')

def parsecodes(codes, len=len, range=range):

    """ Converts code combinations to either a single code integer
        or a tuple of integers.

        meta-codes (in angular brackets, e.g. <LR> and <RL>) are

            

Reported by Pylint.

Redefining built-in 'map'
Error

Line: 138 Column: 33

                      print('* failed to convert %r: %s' % (t, why))
        raise

def python_mapdef_code(varname, map, comments=1, precisions=(2, 4)):

    l = []
    append = l.append
    if "IDENTITY" in map:
        append("%s = codecs.make_identity_dict(range(%d))" %

            

Reported by Pylint.

Redefining built-in 'map'
Error

Line: 195 Column: 35

              
    return l

def python_tabledef_code(varname, map, comments=1, key_precision=2):

    l = []
    append = l.append
    append('%s = (' % varname)


            

Reported by Pylint.

Redefining built-in 'map'
Error

Line: 253 Column: 19

                  append(')')
    return l

def codegen(name, map, encodingname, comments=1):

    """ Returns Python source for the given map.

        Comments are included in the source, if comments is true (default).


            

Reported by Pylint.

Redefining built-in 'map'
Error

Line: 358 Column: 16

              
    return '\n'.join(l).expandtabs()

def pymap(name,map,pyfile,encodingname,comments=1):

    code = codegen(name,map,encodingname,comments)
    with open(pyfile,'w') as f:
        f.write(code)


            

Reported by Pylint.

Unused argument 'name'
Error

Line: 364 Column: 16

                  with open(pyfile,'w') as f:
        f.write(code)

def marshalmap(name,map,marshalfile):

    d = {}
    for e,(u,c) in map.items():
        d[e] = (u,c)
    with open(marshalfile,'wb') as f:

            

Reported by Pylint.

Redefining built-in 'map'
Error

Line: 364 Column: 21

                  with open(pyfile,'w') as f:
        f.write(code)

def marshalmap(name,map,marshalfile):

    d = {}
    for e,(u,c) in map.items():
        d[e] = (u,c)
    with open(marshalfile,'wb') as f:

            

Reported by Pylint.

Lib/xml/sax/handler.py
45 issues
Unused argument 'publicId'
Error

Line: 230 Column: 29

                  resolve all external entities. Note that DefaultHandler implements
    this interface with the default behaviour."""

    def resolveEntity(self, publicId, systemId):
        """Resolve the system identifier of an entity and return either
        the system identifier to read from as a string, or an InputSource
        to read from."""
        return systemId


            

Reported by Pylint.

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

Line: 12 Column: 1

              $Id$
"""

version = '2.0beta'

#============================================================================
#
# HANDLER INTERFACES
#

            

Reported by Pylint.

Method could be a function
Error

Line: 32 Column: 5

                  recoverable errors, and unrecoverable errors. All methods take a
    SAXParseException as the only parameter."""

    def error(self, exception):
        "Handle a recoverable error."
        raise exception

    def fatalError(self, exception):
        "Handle a non-recoverable error."

            

Reported by Pylint.

Method could be a function
Error

Line: 36 Column: 5

                      "Handle a recoverable error."
        raise exception

    def fatalError(self, exception):
        "Handle a non-recoverable error."
        raise exception

    def warning(self, exception):
        "Handle a warning."

            

Reported by Pylint.

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

Line: 36 Column: 5

                      "Handle a recoverable error."
        raise exception

    def fatalError(self, exception):
        "Handle a non-recoverable error."
        raise exception

    def warning(self, exception):
        "Handle a warning."

            

Reported by Pylint.

Method could be a function
Error

Line: 40 Column: 5

                      "Handle a non-recoverable error."
        raise exception

    def warning(self, exception):
        "Handle a warning."
        print(exception)


# ===== CONTENTHANDLER =====

            

Reported by Pylint.

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

Line: 57 Column: 5

                  def __init__(self):
        self._locator = None

    def setDocumentLocator(self, locator):
        """Called by the parser to give the application a locator for
        locating the origin of document events.

        SAX parsers are strongly encouraged (though not absolutely
        required) to supply a locator: if it does so, it must supply

            

Reported by Pylint.

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

Line: 80 Column: 5

                      application should not attempt to use it at any other time."""
        self._locator = locator

    def startDocument(self):
        """Receive notification of the beginning of a document.

        The SAX parser will invoke this method only once, before any
        other methods in this interface or in DTDHandler (except for
        setDocumentLocator)."""

            

Reported by Pylint.

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

Line: 87 Column: 5

                      other methods in this interface or in DTDHandler (except for
        setDocumentLocator)."""

    def endDocument(self):
        """Receive notification of the end of a document.

        The SAX parser will invoke this method only once, and it will
        be the last method invoked during the parse. The parser shall
        not invoke this method until it has either abandoned parsing

            

Reported by Pylint.

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

Line: 96 Column: 5

                      (because of an unrecoverable error) or reached the end of
        input."""

    def startPrefixMapping(self, prefix, uri):
        """Begin the scope of a prefix-URI Namespace mapping.

        The information from this event is not necessary for normal
        Namespace processing: the SAX XML reader will automatically
        replace prefixes for element and attribute names when the

            

Reported by Pylint.

Python/fileutils.c
45 issues
Uninitialized variable: fd
Error

Line: 1507 CWE codes: 908

                          Py_BEGIN_ALLOW_THREADS
            fd = open(pathname, flags);
            Py_END_ALLOW_THREADS
        } while (fd < 0
                 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
        if (async_err) {
            Py_DECREF(pathname_obj);
            return -1;
        }

            

Reported by Cppcheck.

Uninitialized variable: fd
Error

Line: 1513 CWE codes: 908

                          Py_DECREF(pathname_obj);
            return -1;
        }
        if (fd < 0) {
            PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError, pathname_obj, NULL);
            Py_DECREF(pathname_obj);
            return -1;
        }
        Py_DECREF(pathname_obj);

            

Reported by Cppcheck.

Uninitialized variable: f
Error

Line: 1686 CWE codes: 908

                      Py_BEGIN_ALLOW_THREADS
        f = fopen(path_bytes, mode);
        Py_END_ALLOW_THREADS
    } while (f == NULL
             && errno == EINTR && !(async_err = PyErr_CheckSignals()));

    Py_DECREF(bytes);
#endif
    if (async_err)

            

Reported by Cppcheck.

Uninitialized variable: f
Error

Line: 1694 CWE codes: 908

                  if (async_err)
        return NULL;

    if (f == NULL) {
        PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
        return NULL;
    }

    if (set_inheritable(fileno(f), 0, 1, NULL) < 0) {

            

Reported by Cppcheck.

readlink - This accepts filename arguments; if an attacker can move those files or change the link content, a race condition results. Also, it does not terminate with ASCII NUL.
Security

Line: 1896 Column: 11 CWE codes: 362 20
Suggestion: Reconsider approach

                      errno = EINVAL;
        return -1;
    }
    res = readlink(cpath, cbuf, cbuf_len);
    PyMem_RawFree(cpath);
    if (res == -1) {
        return -1;
    }
    if ((size_t)res == cbuf_len) {

            

Reported by FlawFinder.

swprintf - Potential format string problem
Security

Line: 897 Column: 5 CWE codes: 134
Suggestion: Make format string constant

              #ifdef MS_WINDOWS
    wchar_t encoding[23];
    unsigned int ansi_codepage = GetACP();
    swprintf(encoding, Py_ARRAY_LENGTH(encoding), L"cp%u", ansi_codepage);
    encoding[Py_ARRAY_LENGTH(encoding) - 1] = 0;
    return _PyMem_RawWcsdup(encoding);
#else
    const char *encoding = nl_langinfo(CODESET);
    if (!encoding || encoding[0] == '\0') {

            

Reported by FlawFinder.

realpath - This function does not protect against buffer overflows, and some implementations can overflow internally
Security

Line: 1944 Column: 11 CWE codes: 120/785!
Suggestion: Ensure that the destination buffer is at least of size MAXPATHLEN, andto protect against implementation problems, the input argument should also be checked to ensure it is no larger than MAXPATHLEN

                      errno = EINVAL;
        return NULL;
    }
    res = realpath(cpath, cresolved_path);
    PyMem_RawFree(cpath);
    if (res == NULL)
        return NULL;

    wresolved_path = Py_DecodeLocale(cresolved_path, &r);

            

Reported by FlawFinder.

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

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

                      goto error;
    }

    char encoding[20];   /* longest name: "iso_646.irv_1991\0" */
    if (!_Py_normalize_encoding(codeset, encoding, sizeof(encoding))) {
        goto error;
    }

#ifdef __hpux

            

Reported by FlawFinder.

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

Line: 261 Column: 9 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

                  }

    for (unsigned int i=0x80; i<=0xff; i++) {
        char ch[1];
        wchar_t wch[1];
        size_t res;

        unsigned uch = (unsigned char)i;
        ch[0] = (char)uch;

            

Reported by FlawFinder.

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

Line: 262 Column: 9 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

              
    for (unsigned int i=0x80; i<=0xff; i++) {
        char ch[1];
        wchar_t wch[1];
        size_t res;

        unsigned uch = (unsigned char)i;
        ch[0] = (char)uch;
        res = _Py_mbstowcs(wch, ch, 1);

            

Reported by FlawFinder.

Lib/wsgiref/handlers.py
45 issues
Attempted relative import beyond top-level package
Error

Line: 3 Column: 1

              """Base classes for server/gateway implementations"""

from .util import FileWrapper, guess_scheme, is_hop_by_hop
from .headers import Headers

import sys, os, time

__all__ = [
    'BaseHandler', 'SimpleHandler', 'BaseCGIHandler', 'CGIHandler',

            

Reported by Pylint.

Attempted relative import beyond top-level package
Error

Line: 4 Column: 1

              """Base classes for server/gateway implementations"""

from .util import FileWrapper, guess_scheme, is_hop_by_hop
from .headers import Headers

import sys, os, time

__all__ = [
    'BaseHandler', 'SimpleHandler', 'BaseCGIHandler', 'CGIHandler',

            

Reported by Pylint.

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

Line: 367 Column: 1

                      Subclasses may override to retarget the output or change its format.
        """
        try:
            from traceback import print_exception
            stderr = self.get_stderr()
            print_exception(
                exc_info[0], exc_info[1], exc_info[2],
                self.traceback_limit, stderr
            )

            

Reported by Pylint.

Unused variable 'y'
Error

Line: 20 Column: 39

                            "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

def format_date_time(timestamp):
    year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
    return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
        _weekdayname[wd], day, _monthname[month], year, hh, mm, ss
    )

_is_request = {

            

Reported by Pylint.

Unused variable 'z'
Error

Line: 20 Column: 42

                            "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

def format_date_time(timestamp):
    year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
    return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
        _weekdayname[wd], day, _monthname[month], year, hh, mm, ss
    )

_is_request = {

            

Reported by Pylint.

No exception type(s) specified
Error

Line: 143 Column: 9

                          # We expect the client to close the connection abruptly from time
            # to time.
            return
        except:
            try:
                self.handle_error()
            except:
                # If we get an error handling an error, just give up already!
                self.close()

            

Reported by Pylint.

Attribute 'environ' defined outside __init__
Error

Line: 155 Column: 15

                  def setup_environ(self):
        """Set up the environment for one request"""

        env = self.environ = self.os_environ.copy()
        self.add_cgi_vars()

        env['wsgi.input']        = self.get_stdin()
        env['wsgi.errors']       = self.get_stderr()
        env['wsgi.version']      = self.wsgi_version

            

Reported by Pylint.

XXX Try for chunked encoding if origin server and client is 1.1
Error

Line: 214 Column: 3

                          if blocks==1:
                self.headers['Content-Length'] = str(self.bytes_sent)
                return
        # XXX Try for chunked encoding if origin server and client is 1.1


    def cleanup_headers(self):
        """Make any necessary header changes or defaults


            

Reported by Pylint.

XXX check Content-Length and truncate if too many bytes written?
Error

Line: 292 Column: 3

                      else:
            self.bytes_sent += len(data)

        # XXX check Content-Length and truncate if too many bytes written?
        self._write(data)
        self._flush()


    def sendfile(self):

            

Reported by Pylint.

XXX check if content-length was too short?
Error

Line: 326 Column: 3

                          self.headers.setdefault('Content-Length', "0")
            self.send_headers()
        else:
            pass # XXX check if content-length was too short?

    def close(self):
        """Close the iterable (if needed) and reset all instance vars

        Subclasses may want to also drop the client connection.

            

Reported by Pylint.

Lib/unittest/main.py
45 issues
Attempted relative import beyond top-level package
Error

Line: 7 Column: 1

              import argparse
import os

from . import loader, runner
from .signals import installHandler

__unittest = True

MAIN_EXAMPLES = """\

            

Reported by Pylint.

Attempted relative import beyond top-level package
Error

Line: 8 Column: 1

              import os

from . import loader, runner
from .signals import installHandler

__unittest = True

MAIN_EXAMPLES = """\
Examples:

            

Reported by Pylint.

Instance of 'TestProgram' has no 'tests' member; maybe 'test'?
Error

Line: 127 Column: 20

                              self._do_discovery(argv[2:])
                return
            self._main_parser.parse_args(argv[1:], self)
            if not self.tests:
                # this allows "python -m unittest -v" to still work for
                # test discovery.
                self._do_discovery([])
                return
        else:

            

Reported by Pylint.

Instance of 'TestProgram' has no 'tests' member; maybe 'test'?
Error

Line: 135 Column: 12

                      else:
            self._main_parser.parse_args(argv[1:], self)

        if self.tests:
            self.testNames = _convert_names(self.tests)
            if __name__ == '__main__':
                # to support python -m unittest ...
                self.module = None
        elif self.defaultTest is None:

            

Reported by Pylint.

Instance of 'TestProgram' has no 'tests' member; maybe 'test'?
Error

Line: 136 Column: 45

                          self._main_parser.parse_args(argv[1:], self)

        if self.tests:
            self.testNames = _convert_names(self.tests)
            if __name__ == '__main__':
                # to support python -m unittest ...
                self.module = None
        elif self.defaultTest is None:
            # createTests will load tests from self.module

            

Reported by Pylint.

Redefining built-in 'exit'
Error

Line: 67 Column: 21

              
    def __init__(self, module='__main__', defaultTest=None, argv=None,
                    testRunner=None, testLoader=loader.defaultTestLoader,
                    exit=True, verbosity=1, failfast=None, catchbreak=None,
                    buffer=None, warnings=None, *, tb_locals=False):
        if isinstance(module, str):
            self.module = __import__(module)
            for part in module.split('.')[1:]:
                self.module = getattr(self.module, part)

            

Reported by Pylint.

Unused argument 'kwargs'
Error

Line: 111 Column: 1

                      self._print_help()
        sys.exit(2)

    def _print_help(self, *args, **kwargs):
        if self.module is None:
            print(self._main_parser.format_help())
            print(MAIN_EXAMPLES % {'prog': self.progName})
            self._discovery_parser.print_help()
        else:

            

Reported by Pylint.

Unused argument 'args'
Error

Line: 111 Column: 1

                      self._print_help()
        sys.exit(2)

    def _print_help(self, *args, **kwargs):
        if self.module is None:
            print(self._main_parser.format_help())
            print(MAIN_EXAMPLES % {'prog': self.progName})
            self._discovery_parser.print_help()
        else:

            

Reported by Pylint.

Redefining name 'loader' from outer scope (line 7)
Error

Line: 153 Column: 13

                      if self.testNamePatterns:
            self.testLoader.testNamePatterns = self.testNamePatterns
        if from_discovery:
            loader = self.testLoader if Loader is None else Loader()
            self.test = loader.discover(self.start, self.pattern, self.top)
        elif self.testNames is None:
            self.test = self.testLoader.loadTestsFromModule(self.module)
        else:
            self.test = self.testLoader.loadTestsFromNames(self.testNames,

            

Reported by Pylint.

Attribute 'test' defined outside __init__
Error

Line: 154 Column: 13

                          self.testLoader.testNamePatterns = self.testNamePatterns
        if from_discovery:
            loader = self.testLoader if Loader is None else Loader()
            self.test = loader.discover(self.start, self.pattern, self.top)
        elif self.testNames is None:
            self.test = self.testLoader.loadTestsFromModule(self.module)
        else:
            self.test = self.testLoader.loadTestsFromNames(self.testNames,
                                                           self.module)

            

Reported by Pylint.

Lib/test/ann_module.py
45 issues
Undefined variable '__annotations__'
Error

Line: 11 Column: 1

              from typing import Optional
from functools import wraps

__annotations__[1] = 2

class C:

    x = 5; y: Optional['C'] = None


            

Reported by Pylint.

Undefined variable '__annotations__'
Error

Line: 22 Column: 5

              
class M(type):

    __annotations__['123'] = 123
    o: type = object

(pars): bool = True

class D(C):

            

Reported by Pylint.

Bad first argument 'F' given to super()
Error

Line: 41 Column: 9

              
class Y(F):
    def __init__(self):
        super(F, self).__init__(123)

class Meta(type):
    def __new__(meta, name, bases, namespace):
        return super().__new__(meta, name, bases, namespace)


            

Reported by Pylint.

Undefined variable 'List'
Error

Line: 52 Column: 16

                  y: str = 'something else'

def foo(x: int = 10):
    def bar(y: List[str]):
        x: str = 'yes'
    bar()

def dec(func):
    @wraps(func)

            

Reported by Pylint.

No value for argument 'y' in function call
Error

Line: 54 Column: 5

              def foo(x: int = 10):
    def bar(y: List[str]):
        x: str = 'yes'
    bar()

def dec(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)

            

Reported by Pylint.

unsupported operand type(s) for |
Error

Line: 62 Column: 4

                      return func(*args, **kwargs)
    return wrapper

u: int | float

            

Reported by Pylint.

Redefining name 'x' from outer scope (line 18)
Error

Line: 36 Column: 24

              
class F():
    z: int = 5
    def __init__(self, x):
        pass

class Y(F):
    def __init__(self):
        super(F, self).__init__(123)

            

Reported by Pylint.

Unused argument 'x'
Error

Line: 51 Column: 9

                  x: str = 'something'
    y: str = 'something else'

def foo(x: int = 10):
    def bar(y: List[str]):
        x: str = 'yes'
    bar()

def dec(func):

            

Reported by Pylint.

Redefining name 'x' from outer scope (line 18)
Error

Line: 51 Column: 9

                  x: str = 'something'
    y: str = 'something else'

def foo(x: int = 10):
    def bar(y: List[str]):
        x: str = 'yes'
    bar()

def dec(func):

            

Reported by Pylint.

Unused argument 'y'
Error

Line: 52 Column: 13

                  y: str = 'something else'

def foo(x: int = 10):
    def bar(y: List[str]):
        x: str = 'yes'
    bar()

def dec(func):
    @wraps(func)

            

Reported by Pylint.

Lib/test/test_importlib/import_/test_api.py
45 issues
Attempted relative import beyond top-level package
Error

Line: 1 Column: 1

              from .. import util

from importlib import machinery
import sys
import types
import unittest
import warnings

PKG_NAME = 'fine'

            

Reported by Pylint.

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

Line: 48 Column: 14

                  exception when passing in an int for the module name)."""

    def test_raises_ModuleNotFoundError(self):
        with self.assertRaises(ModuleNotFoundError):
            util.import_importlib('some module that does not exist')

    def test_name_requires_rparition(self):
        # Raise TypeError if a non-string is passed in for the module name.
        with self.assertRaises(TypeError):

            

Reported by Pylint.

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

Line: 53 Column: 14

              
    def test_name_requires_rparition(self):
        # Raise TypeError if a non-string is passed in for the module name.
        with self.assertRaises(TypeError):
            self.__import__(42)

    def test_negative_level(self):
        # Raise ValueError when a negative level is specified.
        # PEP 328 did away with sys.module None entries and the ambiguity of

            

Reported by Pylint.

Instance of 'APITest' has no '__import__' member
Error

Line: 54 Column: 13

                  def test_name_requires_rparition(self):
        # Raise TypeError if a non-string is passed in for the module name.
        with self.assertRaises(TypeError):
            self.__import__(42)

    def test_negative_level(self):
        # Raise ValueError when a negative level is specified.
        # PEP 328 did away with sys.module None entries and the ambiguity of
        # absolute/relative imports.

            

Reported by Pylint.

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

Line: 60 Column: 14

                      # Raise ValueError when a negative level is specified.
        # PEP 328 did away with sys.module None entries and the ambiguity of
        # absolute/relative imports.
        with self.assertRaises(ValueError):
            self.__import__('os', globals(), level=-1)

    def test_nonexistent_fromlist_entry(self):
        # If something in fromlist doesn't exist, that's okay.
        # issue15715

            

Reported by Pylint.

Instance of 'APITest' has no '__import__' member
Error

Line: 61 Column: 13

                      # PEP 328 did away with sys.module None entries and the ambiguity of
        # absolute/relative imports.
        with self.assertRaises(ValueError):
            self.__import__('os', globals(), level=-1)

    def test_nonexistent_fromlist_entry(self):
        # If something in fromlist doesn't exist, that's okay.
        # issue15715
        mod = types.ModuleType(PKG_NAME)

            

Reported by Pylint.

Instance of 'APITest' has no 'bad_finder_loader' member
Error

Line: 68 Column: 43

                      # issue15715
        mod = types.ModuleType(PKG_NAME)
        mod.__path__ = ['XXX']
        with util.import_state(meta_path=[self.bad_finder_loader]):
            with util.uncache(PKG_NAME):
                sys.modules[PKG_NAME] = mod
                self.__import__(PKG_NAME, fromlist=['not here'])

    def test_fromlist_load_error_propagates(self):

            

Reported by Pylint.

Instance of 'APITest' has no '__import__' member
Error

Line: 71 Column: 17

                      with util.import_state(meta_path=[self.bad_finder_loader]):
            with util.uncache(PKG_NAME):
                sys.modules[PKG_NAME] = mod
                self.__import__(PKG_NAME, fromlist=['not here'])

    def test_fromlist_load_error_propagates(self):
        # If something in fromlist triggers an exception not related to not
        # existing, let that exception propagate.
        # issue15316

            

Reported by Pylint.

Instance of 'APITest' has no 'bad_finder_loader' member
Error

Line: 79 Column: 43

                      # issue15316
        mod = types.ModuleType(PKG_NAME)
        mod.__path__ = ['XXX']
        with util.import_state(meta_path=[self.bad_finder_loader]):
            with util.uncache(PKG_NAME):
                sys.modules[PKG_NAME] = mod
                with self.assertRaises(ImportError):
                    self.__import__(PKG_NAME,
                                    fromlist=[SUBMOD_NAME.rpartition('.')[-1]])

            

Reported by Pylint.

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

Line: 82 Column: 22

                      with util.import_state(meta_path=[self.bad_finder_loader]):
            with util.uncache(PKG_NAME):
                sys.modules[PKG_NAME] = mod
                with self.assertRaises(ImportError):
                    self.__import__(PKG_NAME,
                                    fromlist=[SUBMOD_NAME.rpartition('.')[-1]])

    def test_blocked_fromlist(self):
        # If fromlist entry is None, let a ModuleNotFoundError propagate.

            

Reported by Pylint.

Lib/distutils/command/install.py
45 issues
Module 'sys' has no 'platlibdir' member
Error

Line: 319 Column: 43

                                          'sys_exec_prefix': exec_prefix,
                            'exec_prefix': exec_prefix,
                            'abiflags': abiflags,
                            'platlibdir': sys.platlibdir,
                           }

        if HAS_USER_SITE:
            self.config_vars['userbase'] = self.install_userbase
            self.config_vars['usersite'] = self.install_usersite

            

Reported by Pylint.

Access to a protected member _INSTALL_SCHEMES of a client class
Error

Line: 44 Column: 22

                          ("unix_prefix", "posix_prefix"), ("unix_home", "posix_home"),
            ("nt", "nt")):
        sys_key = key
        sys_scheme = sysconfig._INSTALL_SCHEMES[sys_scheme_name]
        if key == "headers" and key not in sys_scheme:
            # On POSIX-y platofrms, Python will:
            # - Build from .h files in 'headers' (only there when
            #   building CPython)
            # - Install .h files to 'include'

            

Reported by Pylint.

Attribute 'exec_prefix' defined outside __init__
Error

Line: 277 Column: 17

                      if os.name != "posix":
            if self.exec_prefix:
                self.warn("exec-prefix option ignored on this platform")
                self.exec_prefix = None

        # Now the interesting logic -- so interesting that we farm it out
        # to other methods.  The goal of these methods is to set the final
        # values for the install_{lib,scripts,data,...}  options, using as
        # input a heady brew of prefix, exec_prefix, home, install_base,

            

Reported by Pylint.

Attribute 'config_vars' defined outside __init__
Error

Line: 308 Column: 9

                      except AttributeError:
            # sys.abiflags may not be defined on all platforms.
            abiflags = ''
        self.config_vars = {'dist_name': self.distribution.get_name(),
                            'dist_version': self.distribution.get_version(),
                            'dist_fullname': self.distribution.get_fullname(),
                            'py_version': py_version,
                            'py_version_short': '%d.%d' % sys.version_info[:2],
                            'py_version_nodot': '%d%d' % sys.version_info[:2],

            

Reported by Pylint.

Attribute 'install_lib' defined outside __init__
Error

Line: 359 Column: 17

                      # already specified install_lib, use their selection.
        if self.install_lib is None:
            if self.distribution.ext_modules: # has extensions: non-pure
                self.install_lib = self.install_platlib
            else:
                self.install_lib = self.install_purelib


        # Convert directories from Unix /-separated syntax to the local

            

Reported by Pylint.

Attribute 'install_lib' defined outside __init__
Error

Line: 361 Column: 17

                          if self.distribution.ext_modules: # has extensions: non-pure
                self.install_lib = self.install_platlib
            else:
                self.install_lib = self.install_purelib


        # Convert directories from Unix /-separated syntax to the local
        # convention.
        self.convert_paths('lib', 'purelib', 'platlib',

            

Reported by Pylint.

Attribute 'install_libbase' defined outside __init__
Error

Line: 377 Column: 9

                      # non-packagized module distributions (hello, Numerical Python!) to
        # get their own directories.
        self.handle_extra_path()
        self.install_libbase = self.install_lib # needed for .pth file
        self.install_lib = os.path.join(self.install_lib, self.extra_dirs)

        # If a new root directory was supplied, make all the installation
        # dirs relative to it.
        if self.root is not None:

            

Reported by Pylint.

Attribute 'install_lib' defined outside __init__
Error

Line: 378 Column: 9

                      # get their own directories.
        self.handle_extra_path()
        self.install_libbase = self.install_lib # needed for .pth file
        self.install_lib = os.path.join(self.install_lib, self.extra_dirs)

        # If a new root directory was supplied, make all the installation
        # dirs relative to it.
        if self.root is not None:
            self.change_roots('libbase', 'lib', 'purelib', 'platlib',

            

Reported by Pylint.

Attribute 'install_platbase' defined outside __init__
Error

Line: 433 Column: 33

                          if self.install_userbase is None:
                raise DistutilsPlatformError(
                    "User base directory is not specified")
            self.install_base = self.install_platbase = self.install_userbase
            self.select_scheme("unix_user")
        elif self.home is not None:
            self.install_base = self.install_platbase = self.home
            self.select_scheme("unix_home")
        else:

            

Reported by Pylint.

Attribute 'install_base' defined outside __init__
Error

Line: 433 Column: 13

                          if self.install_userbase is None:
                raise DistutilsPlatformError(
                    "User base directory is not specified")
            self.install_base = self.install_platbase = self.install_userbase
            self.select_scheme("unix_user")
        elif self.home is not None:
            self.install_base = self.install_platbase = self.home
            self.select_scheme("unix_home")
        else:

            

Reported by Pylint.

Lib/email/generator.py
45 issues
XXX: no longer used by the code below.
Error

Line: 19 Column: 3

              from email.utils import _has_surrogates

UNDERSCORE = '_'
NL = '\n'  # XXX: no longer used by the code below.

NLCRE = re.compile(r'\r\n|\r|\n')
fcre = re.compile(r'^From ', re.MULTILINE)



            

Reported by Pylint.

Attribute '_NL' defined outside __init__
Error

Line: 98 Column: 9

                          policy = policy.clone(linesep=linesep)
        if self.maxheaderlen is not None:
            policy = policy.clone(max_line_length=self.maxheaderlen)
        self._NL = policy.linesep
        self._encoded_NL = self._encode(self._NL)
        self._EMPTY = ''
        self._encoded_EMPTY = self._encode(self._EMPTY)
        # Because we use clone (below) when we recursively process message
        # subparts, and because clone uses the computed policy (not None),

            

Reported by Pylint.

Attribute '_encoded_NL' defined outside __init__
Error

Line: 99 Column: 9

                      if self.maxheaderlen is not None:
            policy = policy.clone(max_line_length=self.maxheaderlen)
        self._NL = policy.linesep
        self._encoded_NL = self._encode(self._NL)
        self._EMPTY = ''
        self._encoded_EMPTY = self._encode(self._EMPTY)
        # Because we use clone (below) when we recursively process message
        # subparts, and because clone uses the computed policy (not None),
        # submessages will automatically get set to the computed policy when

            

Reported by Pylint.

Attribute '_EMPTY' defined outside __init__
Error

Line: 100 Column: 9

                          policy = policy.clone(max_line_length=self.maxheaderlen)
        self._NL = policy.linesep
        self._encoded_NL = self._encode(self._NL)
        self._EMPTY = ''
        self._encoded_EMPTY = self._encode(self._EMPTY)
        # Because we use clone (below) when we recursively process message
        # subparts, and because clone uses the computed policy (not None),
        # submessages will automatically get set to the computed policy when
        # they are processed by this code.

            

Reported by Pylint.

Attribute '_encoded_EMPTY' defined outside __init__
Error

Line: 101 Column: 9

                      self._NL = policy.linesep
        self._encoded_NL = self._encode(self._NL)
        self._EMPTY = ''
        self._encoded_EMPTY = self._encode(self._EMPTY)
        # Because we use clone (below) when we recursively process message
        # subparts, and because clone uses the computed policy (not None),
        # submessages will automatically get set to the computed policy when
        # they are processed by this code.
        old_gen_policy = self.policy

            

Reported by Pylint.

XXX logic tells me this else should be needed, but the tests fail
Error

Line: 159 Column: 3

                          self.write(self._NL)
        if lines[-1]:
            self.write(lines[-1])
        # XXX logic tells me this else should be needed, but the tests fail
        # with it and pass without it.  (NLCRE.split ends with a blank element
        # if and only if there was a trailing newline.)
        #else:
        #    self.write(self._NL)


            

Reported by Pylint.

Attribute '_munge_cte' defined outside __init__
Error

Line: 179 Column: 13

                      # necessary.
        oldfp = self._fp
        try:
            self._munge_cte = None
            self._fp = sfp = self._new_buffer()
            self._dispatch(msg)
        finally:
            self._fp = oldfp
            munge_cte = self._munge_cte

            

Reported by Pylint.

Access to a protected member _payload of a client class
Error

Line: 240 Column: 28

                          return
        if not isinstance(payload, str):
            raise TypeError('string payload expected: %s' % type(payload))
        if _has_surrogates(msg._payload):
            charset = msg.get_param('charset')
            if charset is not None:
                # XXX: This copy stuff is an ugly hack to avoid modifying the
                # existing message.
                msg = deepcopy(msg)

            

Reported by Pylint.

XXX: This copy stuff is an ugly hack to avoid modifying the
Error

Line: 243 Column: 3

                      if _has_surrogates(msg._payload):
            charset = msg.get_param('charset')
            if charset is not None:
                # XXX: This copy stuff is an ugly hack to avoid modifying the
                # existing message.
                msg = deepcopy(msg)
                del msg['content-transfer-encoding']
                msg.set_payload(payload, charset)
                payload = msg.get_payload()

            

Reported by Pylint.

Attribute '_munge_cte' defined outside __init__
Error

Line: 249 Column: 17

                              del msg['content-transfer-encoding']
                msg.set_payload(payload, charset)
                payload = msg.get_payload()
                self._munge_cte = (msg['content-transfer-encoding'],
                                   msg['content-type'])
        if self._mangle_from_:
            payload = fcre.sub('>From ', payload)
        self._write_lines(payload)


            

Reported by Pylint.