Fixed several PyLint and Mypy issues

parent 8176cf6e
......@@ -3,6 +3,7 @@ Version 0.13
Released: 2019-02-23
* New GWE official icon! (closes #43)
* A little code cleanup (fixed many PyLint and Mypy issues)
Version 0.12.1
==============
......
......@@ -31,6 +31,7 @@
<description>
<ul>
<li>New GWE official icon! (closes #43)</li>
<li>A little code cleanup (fixed many PyLint and Mypy issues)</li>
</ul>
</description>
</release>
......
......@@ -21,15 +21,14 @@ import locale
import gettext
import logging
import sys
from typing import Type, Any
from types import TracebackType
from typing import Type
from os.path import abspath, join, dirname
from peewee import SqliteDatabase
from rx.disposables import CompositeDisposable
from gi.repository import GLib
from gwe.conf import APP_PACKAGE_NAME
from gwe.model import SpeedStep, FanProfile, CurrentFanProfile, OverclockProfile, CurrentOverclockProfile, Setting
from gi.repository import GLib
from gwe.util.log import set_log_level
from gwe.di import INJECTOR
from gwe.app import Application
......@@ -64,12 +63,12 @@ def _cleanup() -> None:
LOG.exception("Error during cleanup!")
def handle_exception(exc_type: Type[BaseException], exc_value: BaseException, exc_traceback: Any) -> None:
if issubclass(exc_type, KeyboardInterrupt):
sys.__excepthook__(exc_type, exc_value, exc_traceback)
def handle_exception(type_: Type[BaseException], value: BaseException, traceback: TracebackType) -> None:
if issubclass(type_, KeyboardInterrupt):
sys.__excepthook__(type_, value, traceback)
return
LOG.critical("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
LOG.critical("Uncaught exception", exc_info=(type_, value, traceback))
_cleanup()
sys.exit(1)
......
......@@ -22,12 +22,10 @@ from typing import Any, Optional, List
from gi.repository import Gtk, Gio, GLib
from injector import inject
from peewee import SqliteDatabase
from gwe.conf import APP_NAME, APP_ID, APP_VERSION, APP_ICON_NAME
from gwe.di import MainBuilder
from gwe.model import FanProfile, SpeedStep, Setting, CurrentFanProfile, load_fan_db_default_data, OverclockProfile, \
load_overclock_db_default_data, CurrentOverclockProfile
from gwe.model import FanProfile, load_fan_db_default_data, OverclockProfile, load_overclock_db_default_data
from gwe.presenter.main import MainPresenter
from gwe.repository import NvidiaRepository
from gwe.util.deployment import is_flatpak
......
......@@ -107,6 +107,7 @@ class SettingsInteractor:
setting: Setting = Setting.get_or_none(key=key)
if setting is not None:
return int(setting.value)
assert default is not None
return default
@staticmethod
......
......@@ -112,10 +112,12 @@ class EditFanProfilePresenter:
self.view.hide()
def on_delete_step_clicked(self, *_: Any) -> None:
assert self._selected_step is not None
self._selected_step.delete_instance()
self.view.refresh_liststore(self._profile)
def on_save_step_clicked(self, *_: Any) -> None:
assert self._selected_step is not None
self._selected_step.temperature = self.view.get_temperature()
self._selected_step.duty = self.view.get_duty()
self._selected_step.save()
......
......@@ -111,5 +111,4 @@ class EditOverclockProfilePresenter:
if not isinstance(result, bool) or not result:
LOG.exception("Set overclock error: %s", str(result))
return False
else:
return True
return True
......@@ -101,7 +101,8 @@ class HistoricalDataPresenter:
def show(self) -> None:
self.view.show()
def on_dialog_delete_event(self, widget: Gtk.Widget, *_: Any) -> Any:
@staticmethod
def on_dialog_delete_event(widget: Gtk.Widget, *_: Any) -> Any:
return hide_on_delete(widget)
def get_refresh_interval(self) -> int:
......
......@@ -162,6 +162,7 @@ class MainPresenter:
def on_overclock_edit_button_clicked(self, *_: Any) -> None:
gpu_index = 0
profile = self._overclock_profile_selected
assert self._latest_status is not None
overclock = self._latest_status.gpu_status_list[gpu_index].overclock
if profile:
self._edit_overclock_profile_presenter.show_edit(profile, overclock)
......@@ -173,6 +174,7 @@ class MainPresenter:
if self._overclock_profile_selected:
self._overclock_profile_applied = self._overclock_profile_selected
self._refresh_overclock_profile_ui(profile_id=self._overclock_profile_selected.id)
assert self._latest_status is not None
self._composite_disposable.add(self._set_overclock_interactor.execute(
gpu_index,
self._latest_status.gpu_status_list[gpu_index].overclock.perf_level_max,
......@@ -258,17 +260,17 @@ class MainPresenter:
)
def _on_status_updated(self, status: Optional[Status]) -> None:
gpu_index = 0
if status is not None:
was_latest_status_none = self._latest_status is None
self._latest_status = status
if was_latest_status_none:
self._refresh_overclock_profile_ui(True)
gpu_status = status.gpu_status_list[0]
gpu_status = status.gpu_status_list[gpu_index]
self._update_fan(gpu_status)
self.main_view.refresh_status(status)
self._historical_data_presenter.add_status(status)
else:
gpu_index = 0
self._set_fan_speed(gpu_index, manual_control=False)
def _update_fan(self, gpu_status: GpuStatus) -> None:
......@@ -359,6 +361,7 @@ class MainPresenter:
def _refresh_overclock_profile_ui(self, init: bool = False, profile_id: Optional[int] = None) -> None:
gpu_index = 0
current: Optional[CurrentOverclockProfile] = None
assert self._latest_status is not None
if init and self._settings_interactor.get_bool('settings_load_last_profile') \
and self._latest_status.gpu_status_list[gpu_index].overclock.available:
current = CurrentOverclockProfile.get_or_none()
......@@ -386,6 +389,7 @@ class MainPresenter:
def _select_overclock_profile(self, profile_id: int) -> None:
gpu_index = 0
assert self._latest_status is not None
if profile_id == _ADD_NEW_PROFILE_INDEX:
self.main_view.set_apply_overclock_profile_button_enabled(False)
self.main_view.set_edit_overclock_profile_button_enabled(False)
......@@ -438,12 +442,11 @@ class MainPresenter:
LOG.exception("Set overclock error: %s", str(result))
self.main_view.set_statusbar_text('Error applying %s! %s' % (name, str(result)))
return False
elif not result:
if not result:
self.main_view.set_statusbar_text('Error applying %s!' % name)
return False
else:
self.main_view.set_statusbar_text('%s applied' % name.capitalize())
return True
self.main_view.set_statusbar_text('%s applied' % name.capitalize())
return True
def _handle_new_version_response(self, version: Optional[str]) -> None:
if version is not None:
......
......@@ -91,7 +91,7 @@ class NvidiaRepository:
memory_total = None
memory_used = None
mem_info = self._nvml_get_val(py3nvml.nvmlDeviceGetMemoryInfo, handle)
if mem_info:
if mem_info is not None:
memory_used = mem_info.used // 1024 // 1024
memory_total = mem_info.total // 1024 // 1024
util = xlib_display.nvcontrol_get_utilization_rates(gpu)
......@@ -194,7 +194,7 @@ class NvidiaRepository:
# )
gpu_status_list.append(gpu_status)
time2 = time.time()
LOG.debug('Fetching new data took {%.3f} ms' % ((time2 - time1) * 1000.0))
LOG.debug('Fetching new data took {%.3f} ms', ((time2 - time1) * 1000.0))
return Status(gpu_status_list)
except:
LOG.exception("Error while getting status")
......@@ -213,7 +213,7 @@ class NvidiaRepository:
gpu_result = xlib_display.nvcontrol_set_gpu_nvclock_offset(gpu, perf, gpu_offset)
mem_result = xlib_display.nvcontrol_set_mem_transfer_rate_offset(gpu, perf, memory_offset * 2)
xlib_display.close()
return gpu_result and mem_result
return gpu_result is True and mem_result is True
@staticmethod
def set_power_limit(gpu_index: int, limit: int) -> bool:
......@@ -253,14 +253,13 @@ class NvidiaRepository:
return a_function(*args)
except NVMLError as err:
if err.value == NVML_ERROR_NOT_SUPPORTED:
LOG.debug("Function %s not supported" % a_function.__name__)
LOG.debug("Function %s not supported", a_function.__name__)
return None
elif err.value == NVML_ERROR_UNKNOWN:
LOG.warning("Unknown error while executing function %s" % a_function.__name__)
if err.value == NVML_ERROR_UNKNOWN:
LOG.warning("Unknown error while executing function %s", a_function.__name__)
return None
else:
LOG.error("Error value = %d = " % err.value)
raise err
LOG.error("Error value = %d ", err.value)
raise err
def _get_power_from_py3nvml(self, handle: Any) -> Power:
power_con = self._nvml_get_val(py3nvml.nvmlDeviceGetPowerManagementLimitConstraints, handle)
......@@ -277,7 +276,7 @@ class NvidiaRepository:
)
@staticmethod
def _convert_milliwatt_to_watt(milliwatt: Optional[int]) -> float:
def _convert_milliwatt_to_watt(milliwatt: Optional[int]) -> Optional[float]:
return None if milliwatt is None else milliwatt / 1000
def _get_temp_from_py3nvml(self, handle: Any) -> Temp:
......
......@@ -14,10 +14,12 @@
#
# You should have received a copy of the GNU General Public License
# along with gwe. If not, see <http://www.gnu.org/licenses/>.
from typing import Callable, Any
def synchronized_with_attr(lock_name):
def decorator(method):
def synced_method(self, *args, **kws):
def synchronized_with_attr(lock_name: str) -> Any:
def decorator(method: Callable) -> Any:
def synced_method(self: Any, *args: Any, **kws: Any) -> Any:
lock = getattr(self, lock_name)
with lock:
return method(self, *args, **kws)
......
......@@ -16,9 +16,9 @@ class DesktopParser(object):
Read [Desktop Entry] section and save key=values pairs to __property_list
"""
if os.path.exists(self._filename):
with open(self._filename, 'r') as f:
with open(self._filename, 'r') as file:
is_desktop_section = False
for line in f.readlines():
for line in file.readlines():
line = line.strip(' ' + os.linesep)
if line == self.DESKTOP_SECTION:
is_desktop_section = True
......@@ -39,9 +39,9 @@ class DesktopParser(object):
if not os.path.exists(directory):
os.makedirs(directory)
with open(self._filename, 'w') as f:
f.write(os.linesep.join((self.DESKTOP_SECTION,
os.linesep.join(['='.join((k, v.strip())) for k, v in self.__property_list]))))
with open(self._filename, 'w') as file:
file.write(os.linesep.join((self.DESKTOP_SECTION,
os.linesep.join(['='.join((k, v.strip())) for k, v in self.__property_list]))))
def get(self, name: str) -> str:
"""
......
......@@ -33,8 +33,8 @@ def set_autostart_entry(is_enabled: bool) -> None:
desktop_parser = DesktopParser(str(AUTOSTART_FILE_PATH))
if not AUTOSTART_FILE_PATH.is_file():
for k, v in DESKTOP_ENTRY.items():
desktop_parser.set(k, v)
for key, value in DESKTOP_ENTRY.items():
desktop_parser.set(key, value)
desktop_parser.set(DESKTOP_ENTRY_ICON, get_data_path(APP_ICON_NAME))
desktop_parser.set(DESKTOP_ENTRY_EXEC, '%s --hide-window' % APP_PACKAGE_NAME)
......
......@@ -48,59 +48,59 @@ class GraphStackedRenderer(GObject.Object, Dazzle.GraphRenderer):
x_end: int,
y_begin: float,
y_end: float,
cr: cairo.Context,
cairo_context: cairo.Context,
area: cairo.RectangleInt) -> None:
model_iter = Dazzle.GraphModelIter()
cr.save()
cairo_context.save()
if model.get_iter_first(model_iter):
chunk = area.width / (model.props.max_samples - 1) / 2.0
last_x = self._calc_x(model_iter, x_begin, x_end, area.width)
last_y = area.height
last_y = float(area.height)
cr.move_to(last_x, area.height)
cairo_context.move_to(last_x, area.height)
while Dazzle.GraphModel.iter_next(model_iter):
x = self._calc_x(model_iter, x_begin, x_end, area.width)
y = self._calc_y(model_iter, y_begin, y_end, area.height, self._column)
cr.curve_to(last_x + chunk, last_y, last_x + chunk, y, x, y)
cairo_context.curve_to(last_x + chunk, last_y, last_x + chunk, y, x, y)
last_x = x
last_y = y
cr.set_line_width(self._line_width)
cr.set_source_rgba(self._stacked_color_rgba.red,
self._stacked_color_rgba.green,
self._stacked_color_rgba.blue,
self._stacked_color_rgba.alpha)
cr.rel_line_to(0, area.height)
cr.stroke_preserve()
cr.close_path()
cr.fill()
cairo_context.set_line_width(self._line_width)
cairo_context.set_source_rgba(self._stacked_color_rgba.red,
self._stacked_color_rgba.green,
self._stacked_color_rgba.blue,
self._stacked_color_rgba.alpha)
cairo_context.rel_line_to(0, area.height)
cairo_context.stroke_preserve()
cairo_context.close_path()
cairo_context.fill()
if model.get_iter_first(model_iter):
chunk = area.width / (model.props.max_samples - 1) / 2.0
last_x = self._calc_x(model_iter, x_begin, x_end, area.width)
last_y = area.height
last_y = float(area.height)
cr.move_to(last_x, last_y)
cairo_context.move_to(last_x, last_y)
while Dazzle.GraphModel.iter_next(model_iter):
x = self._calc_x(model_iter, x_begin, x_end, area.width)
y = self._calc_y(model_iter, y_begin, y_end, area.height, self._column)
cr.curve_to(last_x + chunk, last_y, last_x + chunk, y, x, y)
cairo_context.curve_to(last_x + chunk, last_y, last_x + chunk, y, x, y)
last_x = x
last_y = y
cr.set_source_rgba(self._stroke_color_rgba.red,
self._stroke_color_rgba.green,
self._stroke_color_rgba.blue,
self._stacked_color_rgba.alpha)
cr.stroke()
cr.restore()
cairo_context.set_source_rgba(self._stroke_color_rgba.red,
self._stroke_color_rgba.green,
self._stroke_color_rgba.blue,
self._stacked_color_rgba.alpha)
cairo_context.stroke()
cairo_context.restore()
@staticmethod
def _calc_x(model_iter: Dazzle.GraphModelIter, begin: float, end: int, width: int) -> float:
......
......@@ -69,7 +69,7 @@ class HistoricalDataView(HistoricalDataViewInterface):
graph_renderer = GraphStackedRenderer()
graph_views.set_hexpand(True)
graph_views.props.height_request = 80
graph_renderer._line_width = 1.5
graph_renderer.set_line_width(1.5)
stroke_color = Gdk.RGBA()
stroke_color.parse(GRAPH_COLOR_HEX)
stacked_color = Gdk.RGBA()
......@@ -118,7 +118,7 @@ class HistoricalDataView(HistoricalDataViewInterface):
self._graph_views[graph_type][1].set_text("%.0f" % max_value)
self._graph_models[graph_type].props.value_max = max(data_tuple[4], max_value)
time2 = time.time()
LOG.debug('Refresh graph took {%.3f} ms' % ((time2 - time1) * 1000.0))
LOG.debug('Refresh graph took {%.3f} ms', ((time2 - time1) * 1000.0))
def show(self) -> None:
self._dialog.show_all()
......
......@@ -19,26 +19,25 @@ import logging
from collections import OrderedDict
from typing import Optional, Dict, List, Tuple, Any
from gwe.di import MainBuilder
from gwe.view.edit_fan_profile import EditFanProfileView
from gwe.util.view import hide_on_delete, init_plot_chart, get_fan_profile_data, is_dazzle_version_supported
from injector import inject, singleton
import gi
from gi.repository import Gtk
from matplotlib.figure import Figure
from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas
from gwe.interactor import SettingsInteractor
from gwe.view.edit_overclock_profile import EditOverclockProfileView
from gwe.view.historical_data import HistoricalDataView
from gwe.view.preferences import PreferencesView
try: # AppIndicator3 may not be installed
import gi
gi.require_version('AppIndicator3', '0.1')
from gi.repository import AppIndicator3
except (ImportError, ValueError):
AppIndicator3 = None
from gwe.di import MainBuilder
from gwe.view.edit_fan_profile import EditFanProfileView
from gwe.util.view import hide_on_delete, init_plot_chart, get_fan_profile_data, is_dazzle_version_supported
from gwe.interactor import SettingsInteractor
from gwe.view.edit_overclock_profile import EditOverclockProfileView
from gwe.view.historical_data import HistoricalDataView
from gwe.view.preferences import PreferencesView
from gwe.model import Status, FanProfile
from gwe.conf import APP_PACKAGE_NAME, APP_ID, APP_NAME, APP_VERSION, APP_SOURCE_URL, APP_ICON_NAME_SYMBOLIC
from gwe.presenter.main import MainPresenter, MainViewInterface
......@@ -127,14 +126,14 @@ class MainView(MainViewInterface):
self._temp_max_gpu_value: Gtk.Label = self._builder.get_object('temp_max_gpu_value')
self._temp_slowdown_value: Gtk.Label = self._builder.get_object('temp_slowdown_value')
self._temp_shutdown_value: Gtk.Label = self._builder.get_object('temp_shutdown_value')
self._fan_duty: Tuple[Gtk.Label] = (
self._fan_duty: Tuple = (
self._builder.get_object('fan_duty_0'),
self._builder.get_object('fan_duty_1'),
self._builder.get_object('fan_duty_2'),
self._builder.get_object('fan_duty_3'),
self._builder.get_object('fan_duty_4')
)
self._fan_rpm: Tuple[Gtk.Label] = (
self._fan_rpm: Tuple = (
self._builder.get_object('fan_rpm_0'),
self._builder.get_object('fan_rpm_1'),
self._builder.get_object('fan_rpm_2'),
......@@ -212,8 +211,9 @@ class MainView(MainViewInterface):
def refresh_status(self, status: Optional[Status]) -> None:
LOG.debug('view status')
gpu_index = 0
if status:
gpu_status = status.gpu_status_list[0]
gpu_status = status.gpu_status_list[gpu_index]
if self._first_refresh:
self._first_refresh = False
self._set_entry_text(self._info_name_entry, gpu_status.info.name)
......
......@@ -64,7 +64,8 @@ disable=missing-docstring,
too-many-arguments,
too-many-instance-attributes,
arguments-differ,
too-few-public-methods
too-few-public-methods,
duplicate-code
# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
......@@ -334,13 +335,7 @@ function-naming-style=snake_case
#function-rgx=
# Good variable names which should always be accepted, separated by a comma.
good-names=i,
j,
k,
ex,
Run,
_,
id
good-names=i,j,k,x,y,z,ex,Run,_,id
# Include a hint for the correct naming format with invalid-name.
include-naming-hint=no
......@@ -424,7 +419,7 @@ max-bool-expr=5
max-branches=12
# Maximum number of locals for function / method body.
max-locals=15
max-locals=20
# Maximum number of parents for a class (see R0901).
max-parents=7
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment