fixed pylint warnings

Change-Id: Ibb3da77e9a53b7293a280659defc029416e30e3b
This commit is contained in:
Alexander Zaft 2022-11-08 07:53:34 +01:00 committed by Enrico Faulhaber
parent a928c95efd
commit c1eb764b09
26 changed files with 59 additions and 50 deletions

View File

@ -52,7 +52,7 @@ disable=missing-docstring
,unneeded-not ,unneeded-not
,unidiomatic-typecheck ,unidiomatic-typecheck
,undefined-loop-variable ,undefined-loop-variable
,consider-using-f-string
[REPORTS] [REPORTS]
# Set the output format. Available formats are text, parseable, colorized, msvs # Set the output format. Available formats are text, parseable, colorized, msvs

View File

@ -76,7 +76,7 @@ def write_config(file_name, tree_widget):
temp_itm_lines[key] = dict_value temp_itm_lines[key] = dict_value
itm_lines.clear() itm_lines.clear()
itm_lines.update(temp_itm_lines) itm_lines.update(temp_itm_lines)
with open(file_name, 'w') as configfile: with open(file_name, 'w', encoding='utf-8') as configfile:
configfile.write('\n'.join(itm_lines.values())) configfile.write('\n'.join(itm_lines.values()))
@ -88,7 +88,8 @@ def read_config(file_path):
node.addChild(ifs) node.addChild(ifs)
node.addChild(mods) node.addChild(mods)
config = configparser.ConfigParser() config = configparser.ConfigParser()
config.read_file(open(file_path)) with open(file_path, encoding='utf-8') as config_file:
config.read_file(config_file)
for section in config.sections(): for section in config.sections():
kind = section.split(' ', 1)[0] kind = section.split(' ', 1)[0]
@ -155,8 +156,8 @@ def get_value(config, section, option):
def get_comments(node, ifs, mods, file_path): def get_comments(node, ifs, mods, file_path):
configfile = open(file_path, 'r') with open(file_path, 'r', encoding='utf-8') as configfile:
all_lines = configfile.readlines() all_lines = configfile.readlines()
current_comment = None current_comment = None
all_ifs = get_all_children_with_names(ifs) all_ifs = get_all_children_with_names(ifs)
all_mods = get_all_children_with_names(mods) all_mods = get_all_children_with_names(mods)
@ -192,6 +193,7 @@ def insert_comment(index, line, all_lines, current_comment, node, all_ifs, all_m
all_ifs, all_mods) all_ifs, all_mods)
# pylint: disable=inconsistent-return-statements
def insert_section_comment(line, current_comment, node, all_ifs, all_mods): def insert_section_comment(line, current_comment, node, all_ifs, all_mods):
try: try:
if line.startswith('[%s' % NODE): if line.startswith('[%s' % NODE):

View File

@ -91,6 +91,7 @@ class QSECNode(QObject):
def syncCommunicate(self, action, ident='', data=None): def syncCommunicate(self, action, ident='', data=None):
reply = self.conn.request(action, ident, data) reply = self.conn.request(action, ident, data)
# pylint: disable=not-an-iterable
return secop.client.encode_msg_frame(*reply).decode('utf-8') return secop.client.encode_msg_frame(*reply).decode('utf-8')
def decode_message(self, msg): def decode_message(self, msg):
@ -106,8 +107,8 @@ class QSECNode(QObject):
def nodeStateChange(self, online, state): def nodeStateChange(self, online, state):
self.stateChange.emit(self.nodename, online, state) self.stateChange.emit(self.nodename, online, state)
def unhandledMessage(self, *msg): def unhandledMessage(self, action, specifier, data):
self.unhandledMsg.emit('%s %s %r' % msg) self.unhandledMsg.emit('%s %s %r' % (action, specifier, data))
class MainWindow(QMainWindow): class MainWindow(QMainWindow):

View File

@ -39,7 +39,7 @@ from secop.gui.util import Value, loadUi
class NodeCtrl(QWidget): class NodeCtrl(QWidget):
def __init__(self, node, parent=None): def __init__(self, node, parent=None):
super(NodeCtrl, self).__init__(parent) super().__init__(parent)
loadUi(self, 'nodectrl.ui') loadUi(self, 'nodectrl.ui')
self._node = node self._node = node
@ -189,7 +189,7 @@ class NodeCtrl(QWidget):
class ReadableWidget(QWidget): class ReadableWidget(QWidget):
def __init__(self, node, module, parent=None): def __init__(self, node, module, parent=None):
super(ReadableWidget, self).__init__(parent) super().__init__(parent)
self._node = node self._node = node
self._module = module self._module = module

View File

@ -29,7 +29,7 @@ from secop.gui.util import loadUi
class ParameterView(QWidget): class ParameterView(QWidget):
def __init__(self, node, module, parameter, parent=None): def __init__(self, node, module, parameter, parent=None):
super(ParameterView, self).__init__(parent) super().__init__(parent)
loadUi(self, 'paramview.ui') loadUi(self, 'paramview.ui')
self._node = node self._node = node
self._module = module self._module = module

View File

@ -36,7 +36,7 @@ from secop.gui.util import loadUi
class StringWidget(QLineEdit): class StringWidget(QLineEdit):
def __init__(self, datatype, readonly=False, parent=None): def __init__(self, datatype, readonly=False, parent=None):
super(StringWidget, self).__init__(parent) super().__init__(parent)
self.datatype = datatype self.datatype = datatype
if readonly: if readonly:
self.setEnabled(False) self.setEnabled(False)
@ -51,7 +51,7 @@ class StringWidget(QLineEdit):
class TextWidget(QTextEdit): class TextWidget(QTextEdit):
def __init__(self, datatype, readonly=False, parent=None): def __init__(self, datatype, readonly=False, parent=None):
super(TextWidget, self).__init__(parent) super().__init__(parent)
self.datatype = datatype self.datatype = datatype
if readonly: if readonly:
self.setEnabled(False) self.setEnabled(False)
@ -72,7 +72,7 @@ class BlobWidget(StringWidget):
# or derive from widget and switch between combobox and radiobuttons? # or derive from widget and switch between combobox and radiobuttons?
class EnumWidget(QComboBox): class EnumWidget(QComboBox):
def __init__(self, datatype, readonly=False, parent=None): def __init__(self, datatype, readonly=False, parent=None):
super(EnumWidget, self).__init__(parent) super().__init__(parent)
self.datatype = datatype self.datatype = datatype
self._map = {} self._map = {}
@ -92,7 +92,7 @@ class EnumWidget(QComboBox):
class BoolWidget(QCheckBox): class BoolWidget(QCheckBox):
def __init__(self, datatype, readonly=False, parent=None): def __init__(self, datatype, readonly=False, parent=None):
super(BoolWidget, self).__init__(parent) super().__init__(parent)
self.datatype = datatype self.datatype = datatype
if readonly: if readonly:
self.setEnabled(False) self.setEnabled(False)
@ -106,7 +106,7 @@ class BoolWidget(QCheckBox):
class IntWidget(QSpinBox): class IntWidget(QSpinBox):
def __init__(self, datatype, readonly=False, parent=None): def __init__(self, datatype, readonly=False, parent=None):
super(IntWidget, self).__init__(parent) super().__init__(parent)
self.datatype = datatype self.datatype = datatype
if readonly: if readonly:
self.setEnabled(False) self.setEnabled(False)
@ -122,7 +122,7 @@ class IntWidget(QSpinBox):
class FloatWidget(QDoubleSpinBox): class FloatWidget(QDoubleSpinBox):
def __init__(self, datatype, readonly=False, parent=None): def __init__(self, datatype, readonly=False, parent=None):
super(FloatWidget, self).__init__(parent) super().__init__(parent)
self.datatype = datatype self.datatype = datatype
if readonly: if readonly:
self.setEnabled(False) self.setEnabled(False)
@ -139,7 +139,7 @@ class FloatWidget(QDoubleSpinBox):
class TupleWidget(QFrame): class TupleWidget(QFrame):
def __init__(self, datatype, readonly=False, parent=None): def __init__(self, datatype, readonly=False, parent=None):
super(TupleWidget, self).__init__(parent) super().__init__(parent)
self.datatypes = datatype.members self.datatypes = datatype.members
@ -164,7 +164,7 @@ class TupleWidget(QFrame):
class StructWidget(QGroupBox): class StructWidget(QGroupBox):
def __init__(self, datatype, readonly=False, parent=None): def __init__(self, datatype, readonly=False, parent=None):
super(StructWidget, self).__init__(parent) super().__init__(parent)
self.layout = QGridLayout() self.layout = QGridLayout()
self.subwidgets = {} self.subwidgets = {}
@ -197,7 +197,7 @@ class StructWidget(QGroupBox):
class ArrayWidget(QGroupBox): class ArrayWidget(QGroupBox):
def __init__(self, datatype, readonly=False, parent=None): def __init__(self, datatype, readonly=False, parent=None):
super(ArrayWidget, self).__init__(parent) super().__init__(parent)
self.datatype = datatype.members self.datatype = datatype.members
self.layout = QVBoxLayout() self.layout = QVBoxLayout()
@ -234,7 +234,7 @@ def get_widget(datatype, readonly=False, parent=None):
class msg(QDialog): class msg(QDialog):
def __init__(self, stuff, parent=None): def __init__(self, stuff, parent=None):
super(msg, self).__init__(parent) super().__init__(parent)
loadUi(self, 'cmddialog.ui') loadUi(self, 'cmddialog.ui')
print(dir(self)) print(dir(self))
self.setWindowTitle('Please enter the arguments for calling command "blubb()"') self.setWindowTitle('Please enter the arguments for calling command "blubb()"')
@ -253,12 +253,12 @@ class msg(QDialog):
def accept(self): def accept(self):
print('accepted') print('accepted')
super(msg, self).accept() super().accept()
def reject(self): def reject(self):
print('rejected') print('rejected')
super(msg, self).reject() super().reject()
def done(self, how): def done(self, how):
print('done(%r)' % how) print('done(%r)' % how)
return super(msg, self).done(how) return super().done(how)

View File

@ -274,7 +274,7 @@ class StringIO(IOBase):
self._conn.send(cmd + self._eol_write) self._conn.send(cmd + self._eol_write)
self.comLog('> %s', cmd.decode(self.encoding)) self.comLog('> %s', cmd.decode(self.encoding))
reply = self._conn.readline(self.timeout) reply = self._conn.readline(self.timeout)
except ConnectionClosed as e: except ConnectionClosed:
self.closeConnection() self.closeConnection()
raise CommunicationFailedError('disconnected') from None raise CommunicationFailedError('disconnected') from None
reply = reply.decode(self.encoding) reply = reply.decode(self.encoding)
@ -372,7 +372,7 @@ class BytesIO(IOBase):
self._conn.send(request) self._conn.send(request)
self.comLog('> %s', hexify(request)) self.comLog('> %s', hexify(request))
reply = self._conn.readbytes(replylen, self.timeout) reply = self._conn.readbytes(replylen, self.timeout)
except ConnectionClosed as e: except ConnectionClosed:
self.closeConnection() self.closeConnection()
raise CommunicationFailedError('disconnected') from None raise CommunicationFailedError('disconnected') from None
self.comLog('< %s', hexify(reply)) self.comLog('< %s', hexify(reply))

View File

@ -131,14 +131,14 @@ class GeneralConfig:
def get(self, key, default=None): def get(self, key, default=None):
"""access for keys not known to exist""" """access for keys not known to exist"""
try: try:
return self.__getitem__(key) return self[key]
except KeyError: except KeyError:
return default return default
def getint(self, key, default=None): def getint(self, key, default=None):
"""access and convert to int""" """access and convert to int"""
try: try:
return int(self.__getitem__(key)) return int(self[key])
except KeyError: except KeyError:
return default return default

View File

@ -32,7 +32,7 @@ def read_pidfile(pidfile):
or None upon errors (file not existing)""" or None upon errors (file not existing)"""
try: try:
with open(pidfile, 'r') as f: with open(pidfile, 'r', encoding='utf-8') as f:
return int(f.read()) return int(f.read())
except (OSError, IOError): except (OSError, IOError):
return None return None
@ -45,7 +45,7 @@ def remove_pidfile(pidfile):
def write_pidfile(pidfile, pid): def write_pidfile(pidfile, pid):
"""write the given pid to the given pidfile""" """write the given pid to the given pidfile"""
with open(pidfile, 'w') as f: with open(pidfile, 'w', encoding='utf-8') as f:
f.write('%d\n' % pid) f.write('%d\n' % pid)
atexit.register(remove_pidfile, pidfile) atexit.register(remove_pidfile, pidfile)

View File

@ -124,7 +124,7 @@ class SequencerMixin:
def seq_is_alive(self): def seq_is_alive(self):
"""Can be called to check if a sequence is currently running.""" """Can be called to check if a sequence is currently running."""
return self._seq_thread and self._seq_thread.isAlive() return self._seq_thread and self._seq_thread.is_alive()
def read_status(self): def read_status(self):
if self.seq_is_alive(): if self.seq_is_alive():

View File

@ -319,6 +319,7 @@ class Module(HasAccessibles):
# 2) check and apply properties specified in cfgdict as # 2) check and apply properties specified in cfgdict as
# '<propertyname> = <propertyvalue>' # '<propertyname> = <propertyvalue>'
# pylint: disable=consider-using-dict-items
for key in self.propertyDict: for key in self.propertyDict:
value = cfgdict.pop(key, None) value = cfgdict.pop(key, None)
if value is None: if value is None:

View File

@ -455,6 +455,7 @@ class Command(Accessible):
- when the argument type is StructOf, the function is called with keyworded arguments - when the argument type is StructOf, the function is called with keyworded arguments
- the validity of the argument/s is/are checked - the validity of the argument/s is/are checked
""" """
# pylint: disable=unnecessary-dunder-call
func = self.__get__(module_obj) func = self.__get__(module_obj)
if self.argument: if self.argument:
# validate # validate

View File

@ -64,6 +64,8 @@ class Parser:
if number is None: if number is None:
return None, text return None, text
try: try:
# TODO: check allthough length is unset in it. 1, number is None, never reaching the try
# pylint: disable=used-before-assignment
return int(text[:length]), text[length:] return int(text[:length]), text[length:]
except ValueError: except ValueError:
return number, text[length:] return number, text[length:]

View File

@ -93,7 +93,7 @@ class PersistentMixin(HasAccessibles):
when a hardware powerdown is detected when a hardware powerdown is detected
""" """
try: try:
with open(self.persistentFile, 'r') as f: with open(self.persistentFile, 'r', encoding='utf-8') as f:
self.persistentData = json.load(f) self.persistentData = json.load(f)
except Exception: except Exception:
self.persistentData = {} self.persistentData = {}
@ -134,7 +134,7 @@ class PersistentMixin(HasAccessibles):
if not os.path.isdir(persistentdir): if not os.path.isdir(persistentdir):
os.makedirs(persistentdir, exist_ok=True) os.makedirs(persistentdir, exist_ok=True)
try: try:
with open(tmpfile, 'w') as f: with open(tmpfile, 'w', encoding='utf-8') as f:
json.dump(self.persistentData, f, indent=2) json.dump(self.persistentData, f, indent=2)
f.write('\n') f.write('\n')
os.rename(tmpfile, self.persistentFile) os.rename(tmpfile, self.persistentFile)

View File

@ -154,6 +154,7 @@ class SecNode(Module):
def request(self, msg): def request(self, msg):
"""send a request, for debugging purposes""" """send a request, for debugging purposes"""
reply = self.secnode.request(*decode_msg(msg.encode('utf-8'))) reply = self.secnode.request(*decode_msg(msg.encode('utf-8')))
# pylint: disable=not-an-iterable
return encode_msg_frame(*reply).decode('utf-8') return encode_msg_frame(*reply).decode('utf-8')

View File

@ -39,7 +39,7 @@ from secop.modules import Attached
try: try:
from daemon import DaemonContext from daemon import DaemonContext
try: try:
import daemon.pidlockfile as pidlockfile from daemon import pidlockfile
except ImportError: except ImportError:
import daemon.pidfile as pidlockfile import daemon.pidfile as pidlockfile
except ImportError: except ImportError:

View File

@ -38,10 +38,10 @@ GIT_REPO = os.path.join(os.path.dirname(__file__), '..', '.git')
def get_git_version(abbrev=4, cwd=None): def get_git_version(abbrev=4, cwd=None):
try: try:
print("REPO:", GIT_REPO) print("REPO:", GIT_REPO)
p = Popen(['git', '--git-dir=%s' % GIT_REPO, with Popen(['git', '--git-dir=%s' % GIT_REPO,
'describe', '--abbrev=%d' % abbrev], 'describe', '--abbrev=%d' % abbrev],
stdout=PIPE, stderr=PIPE) stdout=PIPE, stderr=PIPE) as p:
stdout, _stderr = p.communicate() stdout, _stderr = p.communicate()
version = stdout.strip().decode('utf-8', 'ignore') version = stdout.strip().decode('utf-8', 'ignore')
print("git:", version) print("git:", version)
# mangle version to comply with pep440 # mangle version to comply with pep440
@ -55,14 +55,14 @@ def get_git_version(abbrev=4, cwd=None):
def read_release_version(): def read_release_version():
try: try:
with open(RELEASE_VERSION_FILE) as f: with open(RELEASE_VERSION_FILE, encoding='utf-8') as f:
return f.readline().strip() return f.readline().strip()
except Exception: except Exception:
return None return None
def write_release_version(version): def write_release_version(version):
with open(RELEASE_VERSION_FILE, 'w') as f: with open(RELEASE_VERSION_FILE, 'w', encoding='utf-8') as f:
f.write("%s\n" % version) f.write("%s\n" % version)

View File

@ -355,5 +355,5 @@ class Cryostat(CryoBase):
def shutdown(self): def shutdown(self):
# should be called from server when the server is stopped # should be called from server when the server is stopped
self._stopflag = True self._stopflag = True
if self._thread and self._thread.isAlive(): if self._thread and self._thread.is_alive():
self._thread.join() self._thread.join()

View File

@ -188,7 +188,7 @@ class PpmsSim:
else: else:
self.status.pos = 5 self.status.pos = 5
self.st = sum([self.status[i] << (i * 4) for i in range(4)]) self.st = sum(self.status[i] << (i * 4) for i in range(4))
self.r1 = self.t * 0.1 self.r1 = self.t * 0.1
self.i1 = self.t % 10.0 self.i1 = self.t % 10.0
self.r2 = 1000 / self.t self.r2 = 1000 / self.t

View File

@ -144,7 +144,7 @@ class CalCurve:
try: try:
parser = cls(**args) parser = cls(**args)
with open(filename) as f: with open(filename, encoding='utf-8') as f:
for line in f: for line in f:
parser.parse(line) parser.parse(line)
except Exception as e: except Exception as e:

View File

@ -15,7 +15,7 @@ def constants():
del c del c
@pytest.fixture(scope="session")
# pylint: disable=redefined-builtin # pylint: disable=redefined-builtin
@pytest.fixture(scope="session")
def globals(): def globals():
return dict() return {}

View File

@ -108,7 +108,7 @@ def test_handler():
assert m.read_b() == 7 assert m.read_b() == 7
assert data.pop() == 'b' assert data.pop() == 'b'
assert data == [] assert not data
def test_common_handler(): def test_common_handler():
@ -137,7 +137,7 @@ def test_common_handler():
assert m.a == 3 assert m.a == 3
assert m.b == 2 assert m.b == 2
assert data.pop() == 'write_hdl' assert data.pop() == 'write_hdl'
assert m.writeDict == {} assert not m.writeDict
m.write_b(4) m.write_b(4)
assert m.a == 3 assert m.a == 3
@ -159,7 +159,7 @@ def test_common_handler():
assert m.b == 2.2 assert m.b == 2.2
assert data.pop() == 'read_hdl' assert data.pop() == 'read_hdl'
assert data == [] assert not data
def test_nopoll(): def test_nopoll():

View File

@ -49,7 +49,7 @@ def test_EnumMember():
a += 2 a += 2
# this shall work # this shall work
assert 2 == (a + 1) # pylint: disable=C0122 assert 2 == (a + 1)
assert (a - 1) == 0 assert (a - 1) == 0
assert a assert a
assert a + a assert a + a

View File

@ -54,6 +54,7 @@ class Connection:
@pytest.fixture(name='init') @pytest.fixture(name='init')
def init_(monkeypatch): def init_(monkeypatch):
# pylint: disable=unnecessary-dunder-call
logger.__init__() logger.__init__()
class Playground: class Playground:

View File

@ -542,7 +542,7 @@ def test_generic_access():
assert obj.read_unhandled() assert obj.read_unhandled()
assert updates == {'obj': {'param': 'potato'}} assert updates == {'obj': {'param': 'potato'}}
updates.clear() updates.clear()
assert updates == {} assert not updates
def test_duplicate_handler_name(): def test_duplicate_handler_name():

View File

@ -40,7 +40,7 @@ MSG = [
[(m.EVENTREPLY, 'mod:par', [123, dict(t=12.25)]), b'update mod:par [123, {"t": 12.25}]'], [(m.EVENTREPLY, 'mod:par', [123, dict(t=12.25)]), b'update mod:par [123, {"t": 12.25}]'],
[(m.HEARTBEATREQUEST, '0', None), b'ping 0'], [(m.HEARTBEATREQUEST, '0', None), b'ping 0'],
[(m.HEARTBEATREPLY, None, [None, dict(t=11.75)]), b'pong [null, {"t": 11.75}]'], [(m.HEARTBEATREPLY, None, [None, dict(t=11.75)]), b'pong [null, {"t": 11.75}]'],
[(m.ERRORPREFIX + m.WRITEREQUEST, 'm:p', ['ErrClass', 'text', dict()]), [(m.ERRORPREFIX + m.WRITEREQUEST, 'm:p', ['ErrClass', 'text', {}]),
b'error_change m:p ["ErrClass", "text", {}]'], b'error_change m:p ["ErrClass", "text", {}]'],
] ]
@pytest.mark.parametrize('msg, line', MSG) @pytest.mark.parametrize('msg, line', MSG)