The following issues were found
Lib/_bootsubprocess.py
13 issues
Line: 80
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b605_start_process_with_a_shell.html
try:
# system() spawns a shell
status = os.system(cmd)
exitcode = os.waitstatus_to_exitcode(status)
if exitcode:
raise ValueError(f"Command {cmd!r} returned non-zero "
f"exit status {exitcode!r}")
Reported by Bandit.
Line: 31
Column: 31
else:
# Parent process
_, status = os.waitpid(pid, 0)
self.returncode = os.waitstatus_to_exitcode(status)
return self.returncode
def _check_cmd(cmd):
Reported by Pylint.
Line: 81
Column: 20
try:
# system() spawns a shell
status = os.system(cmd)
exitcode = os.waitstatus_to_exitcode(status)
if exitcode:
raise ValueError(f"Command {cmd!r} returned non-zero "
f"exit status {exitcode!r}")
try:
Reported by Pylint.
Line: 27
Column: 17
else:
os.execv(self._cmd[0], self._cmd)
finally:
os._exit(1)
else:
# Parent process
_, status = os.waitpid(pid, 0)
self.returncode = os.waitstatus_to_exitcode(status)
Reported by Pylint.
Line: 11
Column: 1
# distutils.spawn used by distutils.command.build_ext
# calls subprocess.Popen().wait()
class Popen:
def __init__(self, cmd, env=None):
self._cmd = cmd
self._env = env
self.returncode = None
Reported by Pylint.
Line: 11
Column: 1
# distutils.spawn used by distutils.command.build_ext
# calls subprocess.Popen().wait()
class Popen:
def __init__(self, cmd, env=None):
self._cmd = cmd
self._env = env
self.returncode = None
Reported by Pylint.
Line: 17
Column: 5
self._env = env
self.returncode = None
def wait(self):
pid = os.fork()
if pid == 0:
# Child process
try:
if self._env is not None:
Reported by Pylint.
Line: 23
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b606_start_process_with_no_shell.html
# Child process
try:
if self._env is not None:
os.execve(self._cmd[0], self._cmd, self._env)
else:
os.execv(self._cmd[0], self._cmd)
finally:
os._exit(1)
else:
Reported by Bandit.
Line: 25
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b606_start_process_with_no_shell.html
if self._env is not None:
os.execve(self._cmd[0], self._cmd, self._env)
else:
os.execv(self._cmd[0], self._cmd)
finally:
os._exit(1)
else:
# Parent process
_, status = os.waitpid(pid, 0)
Reported by Bandit.
Line: 40
Column: 13
# Use regex [a-zA-Z0-9./-]+: reject empty string, space, etc.
safe_chars = []
for first, last in (("a", "z"), ("A", "Z"), ("0", "9")):
for ch in range(ord(first), ord(last) + 1):
safe_chars.append(chr(ch))
safe_chars.append("./-")
safe_chars = ''.join(safe_chars)
if isinstance(cmd, (tuple, list)):
Reported by Pylint.
Lib/asyncio/queues.py
13 issues
Line: 6
Column: 1
import collections
import heapq
from . import locks
from . import mixins
class QueueEmpty(Exception):
"""Raised when Queue.get_nowait() is called on an empty Queue."""
Reported by Pylint.
Line: 7
Column: 1
import heapq
from . import locks
from . import mixins
class QueueEmpty(Exception):
"""Raised when Queue.get_nowait() is called on an empty Queue."""
pass
Reported by Pylint.
Line: 12
Column: 5
class QueueEmpty(Exception):
"""Raised when Queue.get_nowait() is called on an empty Queue."""
pass
class QueueFull(Exception):
"""Raised when the Queue.put_nowait() method is called on a full Queue."""
pass
Reported by Pylint.
Line: 17
Column: 5
class QueueFull(Exception):
"""Raised when the Queue.put_nowait() method is called on a full Queue."""
pass
class Queue(mixins._LoopBoundMixin):
"""A queue, useful for coordinating producer and consumer coroutines.
Reported by Pylint.
Line: 20
Column: 13
pass
class Queue(mixins._LoopBoundMixin):
"""A queue, useful for coordinating producer and consumer coroutines.
If maxsize is less than or equal to zero, the queue size is infinite. If it
is an integer greater than 0, then "await put()" will block when the
queue reaches maxsize, until an item is removed by get().
Reported by Pylint.
Line: 47
Column: 21
# These three are overridable in subclasses.
def _init(self, maxsize):
self._queue = collections.deque()
def _get(self):
return self._queue.popleft()
Reported by Pylint.
Line: 72
Column: 32
def __str__(self):
return f'<{type(self).__name__} {self._format()}>'
def __class_getitem__(cls, type):
return cls
def _format(self):
result = f'maxsize={self._maxsize!r}'
if getattr(self, '_queue', None):
Reported by Pylint.
Line: 72
Column: 32
def __str__(self):
return f'<{type(self).__name__} {self._format()}>'
def __class_getitem__(cls, type):
return cls
def _format(self):
result = f'maxsize={self._maxsize!r}'
if getattr(self, '_queue', None):
Reported by Pylint.
Line: 228
Column: 5
def _init(self, maxsize):
self._queue = []
def _put(self, item, heappush=heapq.heappush):
heappush(self._queue, item)
def _get(self, heappop=heapq.heappop):
return heappop(self._queue)
Reported by Pylint.
Line: 231
Column: 5
def _put(self, item, heappush=heapq.heappush):
heappush(self._queue, item)
def _get(self, heappop=heapq.heappop):
return heappop(self._queue)
class LifoQueue(Queue):
"""A subclass of Queue that retrieves most recently added entries first."""
Reported by Pylint.
Lib/ctypes/test/test_unicode.py
13 issues
Line: 34
Column: 9
_fields_ = [("unicode", ctypes.c_wchar_p)]
t = TestStruct()
# This would raise a ValueError:
t.unicode = "foo\0bar\0\0"
func = ctypes.CDLL(_ctypes_test.__file__)._testfunc_p_p
class StringTestCase(UnicodeTestCase):
Reported by Pylint.
Line: 37
Column: 8
t.unicode = "foo\0bar\0\0"
func = ctypes.CDLL(_ctypes_test.__file__)._testfunc_p_p
class StringTestCase(UnicodeTestCase):
def setUp(self):
func.argtypes = [ctypes.c_char_p]
func.restype = ctypes.c_char_p
Reported by Pylint.
Line: 1
Column: 1
import unittest
import ctypes
from ctypes.test import need_symbol
import _ctypes_test
@need_symbol('c_wchar')
class UnicodeTestCase(unittest.TestCase):
def test_wcslen(self):
Reported by Pylint.
Line: 8
Column: 1
import _ctypes_test
@need_symbol('c_wchar')
class UnicodeTestCase(unittest.TestCase):
def test_wcslen(self):
dll = ctypes.CDLL(_ctypes_test.__file__)
wcslen = dll.my_wcslen
wcslen.argtypes = [ctypes.c_wchar_p]
Reported by Pylint.
Line: 9
Column: 5
@need_symbol('c_wchar')
class UnicodeTestCase(unittest.TestCase):
def test_wcslen(self):
dll = ctypes.CDLL(_ctypes_test.__file__)
wcslen = dll.my_wcslen
wcslen.argtypes = [ctypes.c_wchar_p]
self.assertEqual(wcslen("abc"), 3)
Reported by Pylint.
Line: 18
Column: 5
self.assertEqual(wcslen("ab\u2070"), 3)
self.assertRaises(ctypes.ArgumentError, wcslen, b"ab\xe4")
def test_buffers(self):
buf = ctypes.create_unicode_buffer("abc")
self.assertEqual(len(buf), 3+1)
buf = ctypes.create_unicode_buffer("ab\xe4\xf6\xfc")
self.assertEqual(buf[:], "ab\xe4\xf6\xfc\0")
Reported by Pylint.
Line: 29
Column: 5
self.assertEqual(buf[::2], 'a\xe4\xfc')
self.assertEqual(buf[6:5:-1], "")
def test_embedded_null(self):
class TestStruct(ctypes.Structure):
_fields_ = [("unicode", ctypes.c_wchar_p)]
t = TestStruct()
# This would raise a ValueError:
t.unicode = "foo\0bar\0\0"
Reported by Pylint.
Line: 29
Column: 5
self.assertEqual(buf[::2], 'a\xe4\xfc')
self.assertEqual(buf[6:5:-1], "")
def test_embedded_null(self):
class TestStruct(ctypes.Structure):
_fields_ = [("unicode", ctypes.c_wchar_p)]
t = TestStruct()
# This would raise a ValueError:
t.unicode = "foo\0bar\0\0"
Reported by Pylint.
Line: 30
Column: 9
self.assertEqual(buf[6:5:-1], "")
def test_embedded_null(self):
class TestStruct(ctypes.Structure):
_fields_ = [("unicode", ctypes.c_wchar_p)]
t = TestStruct()
# This would raise a ValueError:
t.unicode = "foo\0bar\0\0"
Reported by Pylint.
Line: 30
Column: 9
self.assertEqual(buf[6:5:-1], "")
def test_embedded_null(self):
class TestStruct(ctypes.Structure):
_fields_ = [("unicode", ctypes.c_wchar_p)]
t = TestStruct()
# This would raise a ValueError:
t.unicode = "foo\0bar\0\0"
Reported by Pylint.
Lib/distutils/tests/test_dir_util.py
13 issues
Line: 17
Column: 1
from test.support import run_unittest
class DirUtilTestCase(support.TempdirManager, unittest.TestCase):
def _log(self, msg, *args):
if len(args) > 0:
self._logs.append(msg % args)
else:
Reported by Pylint.
Line: 26
Column: 9
self._logs.append(msg)
def setUp(self):
super(DirUtilTestCase, self).setUp()
self._logs = []
tmp_dir = self.mkdtemp()
self.root_target = os.path.join(tmp_dir, 'deep')
self.target = os.path.join(self.root_target, 'here')
self.target2 = os.path.join(tmp_dir, 'deep2')
Reported by Pylint.
Line: 37
Column: 9
def tearDown(self):
log.info = self.old_log
super(DirUtilTestCase, self).tearDown()
def test_mkpath_remove_tree_verbosity(self):
mkpath(self.target, verbose=0)
wanted = []
Reported by Pylint.
Line: 39
Column: 5
log.info = self.old_log
super(DirUtilTestCase, self).tearDown()
def test_mkpath_remove_tree_verbosity(self):
mkpath(self.target, verbose=0)
wanted = []
self.assertEqual(self._logs, wanted)
remove_tree(self.root_target, verbose=0)
Reported by Pylint.
Line: 58
Column: 5
@unittest.skipIf(sys.platform.startswith('win'),
"This test is only appropriate for POSIX-like systems.")
def test_mkpath_with_custom_mode(self):
# Get and set the current umask value for testing mode bits.
umask = os.umask(0o002)
os.umask(umask)
mkpath(self.target, 0o700)
self.assertEqual(
Reported by Pylint.
Line: 69
Column: 5
self.assertEqual(
stat.S_IMODE(os.stat(self.target2).st_mode), 0o555 & ~umask)
def test_create_tree_verbosity(self):
create_tree(self.root_target, ['one', 'two', 'three'], verbose=0)
self.assertEqual(self._logs, [])
remove_tree(self.root_target, verbose=0)
Reported by Pylint.
Line: 81
Column: 5
remove_tree(self.root_target, verbose=0)
def test_copy_tree_verbosity(self):
mkpath(self.target, verbose=0)
copy_tree(self.target, self.target2, verbose=0)
self.assertEqual(self._logs, [])
Reported by Pylint.
Line: 92
Column: 35
mkpath(self.target, verbose=0)
a_file = os.path.join(self.target, 'ok.txt')
with open(a_file, 'w') as f:
f.write('some content')
wanted = ['copying %s -> %s' % (a_file, self.target2)]
copy_tree(self.target, self.target2, verbose=1)
self.assertEqual(self._logs, wanted)
Reported by Pylint.
Line: 102
Column: 5
remove_tree(self.root_target, verbose=0)
remove_tree(self.target2, verbose=0)
def test_copy_tree_skips_nfs_temp_files(self):
mkpath(self.target, verbose=0)
a_file = os.path.join(self.target, 'ok.txt')
nfs_file = os.path.join(self.target, '.nfs123abc')
for f in a_file, nfs_file:
Reported by Pylint.
Line: 107
Column: 13
a_file = os.path.join(self.target, 'ok.txt')
nfs_file = os.path.join(self.target, '.nfs123abc')
for f in a_file, nfs_file:
with open(f, 'w') as fh:
fh.write('some content')
copy_tree(self.target, self.target2)
self.assertEqual(os.listdir(self.target2), ['ok.txt'])
Reported by Pylint.
Lib/idlelib/idle_test/mock_idle.py
13 issues
Line: 58
Column: 5
'''Minimally imitate undo.UndoDelegator class.
'''
# A real undo block is only needed for user interaction.
def undo_block_start(*args):
pass
def undo_block_stop(*args):
pass
Reported by Pylint.
Line: 60
Column: 5
# A real undo block is only needed for user interaction.
def undo_block_start(*args):
pass
def undo_block_stop(*args):
pass
Reported by Pylint.
Line: 43
Column: 36
class Editor:
'''Minimally imitate editor.EditorWindow class.
'''
def __init__(self, flist=None, filename=None, key=None, root=None,
text=None): # Allow real Text with mock Editor.
self.text = text or Text()
self.undo = UndoDelegator()
def get_selection_indices(self):
Reported by Pylint.
Line: 43
Column: 51
class Editor:
'''Minimally imitate editor.EditorWindow class.
'''
def __init__(self, flist=None, filename=None, key=None, root=None,
text=None): # Allow real Text with mock Editor.
self.text = text or Text()
self.undo = UndoDelegator()
def get_selection_indices(self):
Reported by Pylint.
Line: 43
Column: 61
class Editor:
'''Minimally imitate editor.EditorWindow class.
'''
def __init__(self, flist=None, filename=None, key=None, root=None,
text=None): # Allow real Text with mock Editor.
self.text = text or Text()
self.undo = UndoDelegator()
def get_selection_indices(self):
Reported by Pylint.
Line: 43
Column: 24
class Editor:
'''Minimally imitate editor.EditorWindow class.
'''
def __init__(self, flist=None, filename=None, key=None, root=None,
text=None): # Allow real Text with mock Editor.
self.text = text or Text()
self.undo = UndoDelegator()
def get_selection_indices(self):
Reported by Pylint.
Line: 8
Column: 1
from idlelib.idle_test.mock_tk import Text
class Func:
'''Record call, capture args, return/raise result set by test.
When mock function is called, set or use attributes:
self.called - increment call number even if no args, kwds passed.
self.args - capture positional arguments.
Reported by Pylint.
Line: 32
Column: 9
self.called += 1
self.args = args
self.kwds = kwds
if isinstance(self.result, BaseException):
raise self.result
elif self.return_self:
return self
else:
return self.result
Reported by Pylint.
Line: 40
Column: 1
return self.result
class Editor:
'''Minimally imitate editor.EditorWindow class.
'''
def __init__(self, flist=None, filename=None, key=None, root=None,
text=None): # Allow real Text with mock Editor.
self.text = text or Text()
Reported by Pylint.
Line: 43
Column: 5
class Editor:
'''Minimally imitate editor.EditorWindow class.
'''
def __init__(self, flist=None, filename=None, key=None, root=None,
text=None): # Allow real Text with mock Editor.
self.text = text or Text()
self.undo = UndoDelegator()
def get_selection_indices(self):
Reported by Pylint.
Lib/lib2to3/fixes/fix_print.py
13 issues
Line: 17
Column: 1
"""
# Local imports
from .. import patcomp
from .. import pytree
from ..pgen2 import token
from .. import fixer_base
from ..fixer_util import Name, Call, Comma, String
Reported by Pylint.
Line: 18
Column: 1
# Local imports
from .. import patcomp
from .. import pytree
from ..pgen2 import token
from .. import fixer_base
from ..fixer_util import Name, Call, Comma, String
Reported by Pylint.
Line: 19
Column: 1
# Local imports
from .. import patcomp
from .. import pytree
from ..pgen2 import token
from .. import fixer_base
from ..fixer_util import Name, Call, Comma, String
parend_expr = patcomp.compile_pattern(
Reported by Pylint.
Line: 20
Column: 1
from .. import patcomp
from .. import pytree
from ..pgen2 import token
from .. import fixer_base
from ..fixer_util import Name, Call, Comma, String
parend_expr = patcomp.compile_pattern(
"""atom< '(' [atom|STRING|NAME] ')' >"""
Reported by Pylint.
Line: 21
Column: 1
from .. import pytree
from ..pgen2 import token
from .. import fixer_base
from ..fixer_util import Name, Call, Comma, String
parend_expr = patcomp.compile_pattern(
"""atom< '(' [atom|STRING|NAME] ')' >"""
)
Reported by Pylint.
Line: 78
Column: 3
return n_stmt
def add_kwarg(self, l_nodes, s_kwd, n_expr):
# XXX All this prefix-setting may lose comments (though rarely)
n_expr.prefix = ""
n_argument = pytree.Node(self.syms.argument,
(Name(s_kwd),
pytree.Leaf(token.EQUAL, "="),
n_expr))
Reported by Pylint.
Line: 29
Column: 1
)
class FixPrint(fixer_base.BaseFix):
BM_compatible = True
PATTERN = """
simple_stmt< any* bare='print' any* > | print_stmt
Reported by Pylint.
Line: 37
Column: 5
simple_stmt< any* bare='print' any* > | print_stmt
"""
def transform(self, node, results):
assert results
bare_print = results.get("bare")
if bare_print:
Reported by Pylint.
Line: 37
Column: 5
simple_stmt< any* bare='print' any* > | print_stmt
"""
def transform(self, node, results):
assert results
bare_print = results.get("bare")
if bare_print:
Reported by Pylint.
Line: 38
Suggestion:
https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html
"""
def transform(self, node, results):
assert results
bare_print = results.get("bare")
if bare_print:
# Special-case print all by itself
Reported by Bandit.
Tools/scripts/pickle2db.py
13 issues
Line: 79
Column: 14
dbfile = args[1]
dbopen = None
for opt, arg in opts:
if opt in ("-h", "--hash"):
try:
dbopen = bsddb.hashopen
except AttributeError:
sys.stderr.write("bsddb module unavailable.\n")
Reported by Pylint.
Line: 136
Suggestion:
https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b301-pickle
while 1:
try:
(key, val) = pickle.load(pfile)
except EOFError:
break
db[key] = val
db.close()
Reported by Bandit.
Line: 46
Column: 5
anydbm = None
import sys
try:
import pickle as pickle
except ImportError:
import pickle
prog = sys.argv[0]
Reported by Pylint.
Line: 46
Suggestion:
https://bandit.readthedocs.io/en/latest/blacklists/blacklist_imports.html#b403-import-pickle
anydbm = None
import sys
try:
import pickle as pickle
except ImportError:
import pickle
prog = sys.argv[0]
Reported by Bandit.
Line: 48
Suggestion:
https://bandit.readthedocs.io/en/latest/blacklists/blacklist_imports.html#b403-import-pickle
try:
import pickle as pickle
except ImportError:
import pickle
prog = sys.argv[0]
def usage():
sys.stderr.write(__doc__ % globals())
Reported by Bandit.
Line: 52
Column: 1
prog = sys.argv[0]
def usage():
sys.stderr.write(__doc__ % globals())
def main(args):
try:
opts, args = getopt.getopt(args, "hbrdag",
Reported by Pylint.
Line: 55
Column: 1
def usage():
sys.stderr.write(__doc__ % globals())
def main(args):
try:
opts, args = getopt.getopt(args, "hbrdag",
["hash", "btree", "recno", "dbm", "anydbm",
"gdbm"])
except getopt.error:
Reported by Pylint.
Line: 55
Column: 1
def usage():
sys.stderr.write(__doc__ % globals())
def main(args):
try:
opts, args = getopt.getopt(args, "hbrdag",
["hash", "btree", "recno", "dbm", "anydbm",
"gdbm"])
except getopt.error:
Reported by Pylint.
Line: 55
Column: 1
def usage():
sys.stderr.write(__doc__ % globals())
def main(args):
try:
opts, args = getopt.getopt(args, "hbrdag",
["hash", "btree", "recno", "dbm", "anydbm",
"gdbm"])
except getopt.error:
Reported by Pylint.
Line: 55
Column: 1
def usage():
sys.stderr.write(__doc__ % globals())
def main(args):
try:
opts, args = getopt.getopt(args, "hbrdag",
["hash", "btree", "recno", "dbm", "anydbm",
"gdbm"])
except getopt.error:
Reported by Pylint.
Tools/scripts/pep384_macrocheck.py
13 issues
Line: 37
Column: 5
raise ValueError("file {} was not found in {}\n"
"Please give the path to Python's include directory."
.format(search, startpath))
errors = 0
with open(name) as python_h:
while True:
line = python_h.readline()
if not line:
break
Reported by Pylint.
Line: 86
Column: 9
while True:
line = yield limited[-1]
new_status = ifdef_level.send(line)
dir = new_status - status
status = new_status
if dir == 1:
if re.match(unlimited_pattern, line):
limited.append(-1)
wait_for = status - 1
Reported by Pylint.
Line: 109
Column: 5
limited.append(-limited.pop()) # negate top
def parse_file(fname):
errors = 0
with open(fname) as f:
lines = f.readlines()
type_pattern = r"^.*?->\s*tp_"
define_pattern = r"^\s*#\s*define\s+(\w+)"
limited = limited_gen()
Reported by Pylint.
Line: 23
Column: 1
DEBUG = False
def dprint(*args, **kw):
if DEBUG:
print(*args, **kw)
def parse_headerfiles(startpath):
"""
Reported by Pylint.
Line: 81
Column: 14
])
else_pattern = r"^\s*#\s*else"
ifdef_level = ifdef_level_gen()
status = next(ifdef_level)
wait_for = -1
while True:
line = yield limited[-1]
new_status = ifdef_level.send(line)
dir = new_status - status
Reported by Pylint.
Line: 108
Column: 1
elif re.match(else_pattern, line):
limited.append(-limited.pop()) # negate top
def parse_file(fname):
errors = 0
with open(fname) as f:
lines = f.readlines()
type_pattern = r"^.*?->\s*tp_"
define_pattern = r"^\s*#\s*define\s+(\w+)"
Reported by Pylint.
Line: 110
Column: 25
def parse_file(fname):
errors = 0
with open(fname) as f:
lines = f.readlines()
type_pattern = r"^.*?->\s*tp_"
define_pattern = r"^\s*#\s*define\s+(\w+)"
limited = limited_gen()
status = next(limited)
Reported by Pylint.
Line: 116
Column: 9
define_pattern = r"^\s*#\s*define\s+(\w+)"
limited = limited_gen()
status = next(limited)
for nr, line in enumerate(lines):
status = limited.send(line)
line = line.rstrip()
dprint(fname, nr, status, line)
if status != -1:
if re.match(define_pattern, line):
Reported by Pylint.
Line: 137
Column: 1
errors += 1
return errors
def report(fname, nr, macro):
f = sys.stderr
print(fname + ":" + str(nr), file=f)
print(macro, file=f)
if __name__ == "__main__":
Reported by Pylint.
Line: 137
Column: 1
errors += 1
return errors
def report(fname, nr, macro):
f = sys.stderr
print(fname + ":" + str(nr), file=f)
print(macro, file=f)
if __name__ == "__main__":
Reported by Pylint.
Tools/scripts/ptags.py
13 issues
Line: 33
Column: 5
def treat_file(filename):
try:
fp = open(filename, 'r')
except:
sys.stderr.write('Cannot open %s\n' % filename)
return
with fp:
base = os.path.basename(filename)
if base[-3:] == '.py':
Reported by Pylint.
Line: 1
Column: 1
#! /usr/bin/env python3
# ptags
#
# Create a tags file for Python programs, usable with vi.
# Tagged are:
# - functions (even inside other defs or classes)
# - classes
# - filenames
Reported by Pylint.
Line: 13
Column: 1
# Warns about files it cannot open.
# No warnings about duplicate tags.
import sys, re, os
tags = [] # Modified global variable!
def main():
args = sys.argv[1:]
Reported by Pylint.
Line: 17
Column: 1
tags = [] # Modified global variable!
def main():
args = sys.argv[1:]
for filename in args:
treat_file(filename)
if tags:
with open('tags', 'w') as fp:
Reported by Pylint.
Line: 22
Column: 35
for filename in args:
treat_file(filename)
if tags:
with open('tags', 'w') as fp:
tags.sort()
for s in tags: fp.write(s)
expr = r'^[ \t]*(def|class)[ \t]+([a-zA-Z0-9_]+)[ \t]*[:\(]'
Reported by Pylint.
Line: 24
Column: 28
if tags:
with open('tags', 'w') as fp:
tags.sort()
for s in tags: fp.write(s)
expr = r'^[ \t]*(def|class)[ \t]+([a-zA-Z0-9_]+)[ \t]*[:\(]'
matcher = re.compile(expr)
Reported by Pylint.
Line: 24
Column: 17
if tags:
with open('tags', 'w') as fp:
tags.sort()
for s in tags: fp.write(s)
expr = r'^[ \t]*(def|class)[ \t]+([a-zA-Z0-9_]+)[ \t]*[:\(]'
matcher = re.compile(expr)
Reported by Pylint.
Line: 27
Column: 1
for s in tags: fp.write(s)
expr = r'^[ \t]*(def|class)[ \t]+([a-zA-Z0-9_]+)[ \t]*[:\(]'
matcher = re.compile(expr)
def treat_file(filename):
try:
fp = open(filename, 'r')
Reported by Pylint.
Line: 30
Column: 1
expr = r'^[ \t]*(def|class)[ \t]+([a-zA-Z0-9_]+)[ \t]*[:\(]'
matcher = re.compile(expr)
def treat_file(filename):
try:
fp = open(filename, 'r')
except:
sys.stderr.write('Cannot open %s\n' % filename)
return
Reported by Pylint.
Line: 32
Column: 9
def treat_file(filename):
try:
fp = open(filename, 'r')
except:
sys.stderr.write('Cannot open %s\n' % filename)
return
with fp:
base = os.path.basename(filename)
Reported by Pylint.
Tools/peg_generator/pegen/tokenizer.py
13 issues
Line: 73
Column: 16
tok.type < tokenize.NEWLINE or tok.type > tokenize.DEDENT
):
break
return tok
def get_lines(self, line_numbers: List[int]) -> List[str]:
"""Retrieve source lines corresponding to line numbers."""
if self._lines:
lines = self._lines
Reported by Pylint.
Line: 1
Column: 1
import token
import tokenize
from typing import Dict, Iterator, List
Mark = int # NewType('Mark', int)
exact_token_types = token.EXACT_TOKEN_TYPES
Reported by Pylint.
Line: 10
Column: 1
exact_token_types = token.EXACT_TOKEN_TYPES
def shorttok(tok: tokenize.TokenInfo) -> str:
return "%-25.25s" % f"{tok.start[0]}.{tok.start[1]}: {token.tok_name[tok.type]}:{tok.string!r}"
class Tokenizer:
"""Caching wrapper for the tokenize module.
Reported by Pylint.
Line: 36
Column: 18
def getnext(self) -> tokenize.TokenInfo:
"""Return the next token and updates the index."""
cached = not self._index == len(self._tokens)
tok = self.peek()
self._index += 1
if self._verbose:
self.report(cached, False)
return tok
Reported by Pylint.
Line: 62
Column: 5
self._lines[tok.start[0]] = tok.line
return self._tokens[self._index]
def diagnose(self) -> tokenize.TokenInfo:
if not self._tokens:
self.getnext()
return self._tokens[-1]
def get_last_non_whitespace_token(self) -> tokenize.TokenInfo:
Reported by Pylint.
Line: 67
Column: 5
self.getnext()
return self._tokens[-1]
def get_last_non_whitespace_token(self) -> tokenize.TokenInfo:
for tok in reversed(self._tokens[: self._index]):
if tok.type != tokenize.ENDMARKER and (
tok.type < tokenize.NEWLINE or tok.type > tokenize.DEDENT
):
break
Reported by Pylint.
Line: 80
Column: 13
if self._lines:
lines = self._lines
else:
n = len(line_numbers)
lines = {}
count = 0
seen = 0
with open(self._path) as f:
for l in f:
Reported by Pylint.
Line: 84
Column: 38
lines = {}
count = 0
seen = 0
with open(self._path) as f:
for l in f:
count += 1
if count in line_numbers:
seen += 1
lines[count] = l
Reported by Pylint.
Line: 85
Column: 21
count = 0
seen = 0
with open(self._path) as f:
for l in f:
count += 1
if count in line_numbers:
seen += 1
lines[count] = l
if seen == n:
Reported by Pylint.
Line: 95
Column: 5
return [lines[n] for n in line_numbers]
def mark(self) -> Mark:
return self._index
def reset(self, index: Mark) -> None:
if index == self._index:
return
Reported by Pylint.