From b4c2a4c24ade50d6bc4b46a2054bc7679636360f Mon Sep 17 00:00:00 2001 From: Bharath Vignesh J K <52282402+RazCrimson@users.noreply.github.com> Date: Fri, 17 May 2024 02:31:54 +0530 Subject: [PATCH] chg: ruff - flake-return fixes --- glances/amps/amp.py | 12 ++-- glances/attribute.py | 3 +- glances/autodiscover.py | 3 +- glances/client.py | 10 +-- glances/client_browser.py | 3 +- glances/cpu_percent.py | 3 +- glances/events_list.py | 3 +- glances/exports/export.py | 3 +- glances/exports/glances_graphite/__init__.py | 4 +- glances/exports/glances_influxdb2/__init__.py | 3 +- glances/exports/glances_rabbitmq/__init__.py | 7 +- glances/exports/glances_riemann/__init__.py | 17 +++-- glances/exports/glances_statsd/__init__.py | 4 +- glances/filter.py | 6 +- glances/folder_list.py | 3 +- glances/globals.py | 8 +-- glances/outputs/glances_bars.py | 1 + glances/outputs/glances_curses.py | 40 ++++++----- glances/outputs/glances_sparklines.py | 1 + glances/outputs/glances_stdout_apidoc.py | 3 +- glances/outputs/glances_unicode.py | 3 +- glances/password.py | 7 +- glances/password_list.py | 12 ++-- glances/plugins/alert/__init__.py | 3 +- glances/plugins/amps/__init__.py | 12 ++-- glances/plugins/containers/__init__.py | 13 ++-- glances/plugins/containers/engines/docker.py | 3 +- glances/plugins/fs/__init__.py | 6 +- glances/plugins/gpu/cards/amd.py | 12 ++-- glances/plugins/load/__init__.py | 6 +- glances/plugins/plugin/model.py | 71 ++++++++----------- glances/plugins/ports/__init__.py | 3 +- glances/plugins/processlist/__init__.py | 9 ++- glances/plugins/raid/__init__.py | 2 +- glances/plugins/sensors/__init__.py | 12 ++-- glances/plugins/uptime/__init__.py | 4 +- glances/processes.py | 3 +- glances/secure.py | 2 +- glances/server.py | 8 +-- glances/stats.py | 24 +++---- glances/thresholds.py | 13 ++-- pyproject.toml | 2 +- setup.py | 4 +- 43 files changed, 154 insertions(+), 217 deletions(-) diff --git a/glances/amps/amp.py b/glances/amps/amp.py index b34063af..61a3b0a4 100644 --- a/glances/amps/amp.py +++ b/glances/amps/amp.py @@ -109,16 +109,14 @@ class GlancesAmp(object): """Generic method to get the item in the AMP configuration""" if key in self.configs: return self.configs[key] - else: - return None + return None def enable(self): """Return True|False if the AMP is enabled in the configuration file (enable=true|false).""" ret = self.get('enable') if ret is None: return False - else: - return ret.lower().startswith('true') + return ret.lower().startswith('true') def regex(self): """Return regular expression used to identified the current application.""" @@ -133,8 +131,7 @@ class GlancesAmp(object): ret = self.get('one_line') if ret is None: return False - else: - return ret.lower().startswith('true') + return ret.lower().startswith('true') def time_until_refresh(self): """Return time in seconds until refresh.""" @@ -193,5 +190,4 @@ class GlancesAmp(object): # Call the children update method if self.should_update(): return self.update(process_list) - else: - return self.result() + return self.result() diff --git a/glances/attribute.py b/glances/attribute.py index 4c6c7767..22f25ef2 100644 --- a/glances/attribute.py +++ b/glances/attribute.py @@ -66,8 +66,7 @@ class GlancesAttribute(object): def value(self): if self.history_len() > 0: return (self._value[1] - self.history_value()[1]) / (self._value[0] - self.history_value()[0]) - else: - return None + return None @value.setter def value(self, new_value): diff --git a/glances/autodiscover.py b/glances/autodiscover.py index 336af140..9b784697 100644 --- a/glances/autodiscover.py +++ b/glances/autodiscover.py @@ -148,8 +148,7 @@ class GlancesAutoDiscoverServer(object): """Return the current server list (dict of dict).""" if zeroconf_tag and self.zeroconf_enable_tag: return self.listener.get_servers_list() - else: - return [] + return [] def set_server(self, server_pos, key, value): """Set the key to the value for the server_pos (position in the list).""" diff --git a/glances/client.py b/glances/client.py index 1412d1e1..c4cfe185 100644 --- a/glances/client.py +++ b/glances/client.py @@ -182,12 +182,12 @@ class GlancesClient(object): """Update stats from Glances/SNMP server.""" if self.client_mode == 'glances': return self.update_glances() - elif self.client_mode == 'snmp': + if self.client_mode == 'snmp': return self.update_snmp() - else: - self.end() - logger.critical("Unknown server mode: {}".format(self.client_mode)) - sys.exit(2) + + self.end() + logger.critical("Unknown server mode: {}".format(self.client_mode)) + sys.exit(2) def update_glances(self): """Get stats from Glances server. diff --git a/glances/client_browser.py b/glances/client_browser.py index c8ba9a8a..1409d316 100644 --- a/glances/client_browser.py +++ b/glances/client_browser.py @@ -77,8 +77,7 @@ class GlancesClientBrowser(object): if clear_password is not None: server['password'] = self.password.get_hash(clear_password) return 'http://{}:{}@{}:{}'.format(server['username'], server['password'], server['ip'], server['port']) - else: - return 'http://{}:{}'.format(server['ip'], server['port']) + return 'http://{}:{}'.format(server['ip'], server['port']) def __update_stats(self, server): """Update stats for the given server (picked from the server list)""" diff --git a/glances/cpu_percent.py b/glances/cpu_percent.py index f978f863..e6fe96ec 100644 --- a/glances/cpu_percent.py +++ b/glances/cpu_percent.py @@ -46,8 +46,7 @@ class CpuPercent(object): If percpu, return the percpu stats""" if percpu: return self.__get_percpu() - else: - return self.__get_cpu() + return self.__get_cpu() def get_info(self): """Get additional information about the CPU""" diff --git a/glances/events_list.py b/glances/events_list.py index b50ec83f..e1105d5f 100644 --- a/glances/events_list.py +++ b/glances/events_list.py @@ -158,8 +158,7 @@ def build_global_message(): if themax['weight'] >= themax['thresholds_min']: # Check if the weight is > to the minimal threshold value return themax['msg'] - else: - return tree[0]['msg'] + return tree[0]['msg'] class GlancesEventsList(object): diff --git a/glances/exports/export.py b/glances/exports/export.py index 4b57a122..b92654ea 100644 --- a/glances/exports/export.py +++ b/glances/exports/export.py @@ -122,8 +122,7 @@ class GlancesExport(object): logger.error("No 'key' available in {}".format(item)) if isinstance(ret, list): return ret[0] - else: - return ret + return ret def parse_tags(self, tags): """Parse tags into a dict. diff --git a/glances/exports/glances_graphite/__init__.py b/glances/exports/glances_graphite/__init__.py index 84289238..2defe864 100644 --- a/glances/exports/glances_graphite/__init__.py +++ b/glances/exports/glances_graphite/__init__.py @@ -100,6 +100,4 @@ def normalize(name): """Normalize name for the Graphite convention""" # Name should not contain space - ret = name.replace(' ', '_') - - return ret + return name.replace(' ', '_') diff --git a/glances/exports/glances_influxdb2/__init__.py b/glances/exports/glances_influxdb2/__init__.py index 8b8ea964..7e10b8b3 100644 --- a/glances/exports/glances_influxdb2/__init__.py +++ b/glances/exports/glances_influxdb2/__init__.py @@ -84,7 +84,7 @@ class Export(GlancesExport): ) # Create the write client - write_client = client.write_api( + return client.write_api( write_options=WriteOptions( batch_size=500, flush_interval=self.interval * 1000, @@ -95,7 +95,6 @@ class Export(GlancesExport): exponential_base=2, ) ) - return write_client def _normalize(self, name, columns, points): """Normalize data for the InfluxDB's data model. diff --git a/glances/exports/glances_rabbitmq/__init__.py b/glances/exports/glances_rabbitmq/__init__.py index 0cec274e..5d481aa1 100644 --- a/glances/exports/glances_rabbitmq/__init__.py +++ b/glances/exports/glances_rabbitmq/__init__.py @@ -67,8 +67,7 @@ class Export(GlancesExport): self.protocol + '://' + self.user + ':' + self.password + '@' + self.host + ':' + self.port + '/' ) connection = pika.BlockingConnection(parameters) - channel = connection.channel() - return channel + return connection.channel() except Exception as e: logger.critical("Connection to rabbitMQ server %s:%s failed. %s" % (self.host, self.port, e)) sys.exit(2) @@ -79,8 +78,8 @@ class Export(GlancesExport): for i in range(len(columns)): if not isinstance(points[i], Number): continue - else: - data += ", " + columns[i] + "=" + str(points[i]) + data += ", " + columns[i] + "=" + str(points[i]) + logger.debug(data) try: self.client.basic_publish(exchange='', routing_key=self.queue, body=data) diff --git a/glances/exports/glances_riemann/__init__.py b/glances/exports/glances_riemann/__init__.py index 79dd2cb8..50e12e05 100644 --- a/glances/exports/glances_riemann/__init__.py +++ b/glances/exports/glances_riemann/__init__.py @@ -48,8 +48,7 @@ class Export(GlancesExport): if not self.export_enable: return None try: - client = bernhard.Client(host=self.host, port=self.port) - return client + return bernhard.Client(host=self.host, port=self.port) except Exception as e: logger.critical("Connection to Riemann failed : %s " % e) return None @@ -59,10 +58,10 @@ class Export(GlancesExport): for i in range(len(columns)): if not isinstance(points[i], Number): continue - else: - data = {'host': self.hostname, 'service': name + " " + columns[i], 'metric': points[i]} - logger.debug(data) - try: - self.client.send(data) - except Exception as e: - logger.error("Cannot export stats to Riemann (%s)" % e) + + data = {'host': self.hostname, 'service': name + " " + columns[i], 'metric': points[i]} + logger.debug(data) + try: + self.client.send(data) + except Exception as e: + logger.error("Cannot export stats to Riemann (%s)" % e) diff --git a/glances/exports/glances_statsd/__init__.py b/glances/exports/glances_statsd/__init__.py index d65c36ca..89dd3f33 100644 --- a/glances/exports/glances_statsd/__init__.py +++ b/glances/exports/glances_statsd/__init__.py @@ -69,6 +69,4 @@ def normalize(name): # Name should not contain some specials chars (issue #1068) ret = name.replace(':', '') ret = ret.replace('%', '') - ret = ret.replace(' ', '_') - - return ret + return ret.replace(' ', '_') diff --git a/glances/filter.py b/glances/filter.py index c0a4a529..e2061277 100644 --- a/glances/filter.py +++ b/glances/filter.py @@ -156,9 +156,9 @@ class GlancesFilter(object): if self.filter_key is None: # Apply filter on command line and process name return self._is_process_filtered(process, key='name') or self._is_process_filtered(process, key='cmdline') - else: - # Apply filter on - return self._is_process_filtered(process) + + # Apply filter on + return self._is_process_filtered(process) def _is_process_filtered(self, process, key=None): """Return True if the process[key] should be filtered according to the current filter""" diff --git a/glances/folder_list.py b/glances/folder_list.py index 5820e847..2211e5f6 100644 --- a/glances/folder_list.py +++ b/glances/folder_list.py @@ -67,8 +67,7 @@ class FolderList(object): value['path'] = self.config.get_value(section, key + 'path') if value['path'] is None: continue - else: - value['path'] = nativestr(value['path']) + value['path'] = nativestr(value['path']) # Optional conf keys # Refresh time diff --git a/glances/globals.py b/glances/globals.py index e18a9f35..43c3b697 100644 --- a/glances/globals.py +++ b/glances/globals.py @@ -128,10 +128,9 @@ def b(s, errors='replace'): def nativestr(s, errors='replace'): if isinstance(s, text_type): return s - elif isinstance(s, (int, float)): + if isinstance(s, (int, float)): return s.__str__() - else: - return s.decode('utf-8', errors=errors) + return s.decode('utf-8', errors=errors) def system_exec(command): @@ -331,8 +330,7 @@ def json_dumps_dictlist(data, item): dl = dictlist(data, item) if dl is None: return None - else: - return json_dumps(dl) + return json_dumps(dl) def string_value_to_float(s): diff --git a/glances/outputs/glances_bars.py b/glances/outputs/glances_bars.py index d434c0f9..d6012b9a 100644 --- a/glances/outputs/glances_bars.py +++ b/glances/outputs/glances_bars.py @@ -76,6 +76,7 @@ class Bar(object): return self.__size if self.__display_value: return self.__size - 6 + return None @property def percent(self): diff --git a/glances/outputs/glances_curses.py b/glances/outputs/glances_curses.py index bed7970a..5a8321af 100644 --- a/glances/outputs/glances_curses.py +++ b/glances/outputs/glances_curses.py @@ -154,9 +154,9 @@ class _GlancesCurses(object): logger.info("Cannot init the curses library, quiet mode on and export.") args.quiet = True return - else: - logger.critical("Cannot init the curses library ({})".format(e)) - sys.exit(1) + + logger.critical("Cannot init the curses library ({})".format(e)) + sys.exit(1) # Load configuration file self.load_config(config) @@ -359,8 +359,7 @@ class _GlancesCurses(object): def get_key(self, window): # TODO: Check issue #163 - ret = window.getch() - return ret + return window.getch() def __catch_key(self, return_to_browser=False): # Catch the pressed key @@ -990,7 +989,8 @@ class _GlancesCurses(object): popup.refresh() self.wait(duration * 1000) return True - elif popup_type == 'input': + + if popup_type == 'input': logger.info(popup_type) logger.info(is_password) # Create a sub-window for the text field @@ -1010,17 +1010,17 @@ class _GlancesCurses(object): self.set_cursor(0) if textbox != '': return textbox - else: - return None - else: - textbox = GlancesTextbox(sub_pop, insert_mode=True) - textbox.edit() - self.set_cursor(0) - if textbox.gather() != '': - return textbox.gather()[:-1] - else: - return None - elif popup_type == 'yesno': + return None + + # No password + textbox = GlancesTextbox(sub_pop, insert_mode=True) + textbox.edit() + self.set_cursor(0) + if textbox.gather() != '': + return textbox.gather()[:-1] + return None + + if popup_type == 'yesno': # # Create a sub-window for the text field sub_pop = popup.derwin(1, 2, len(sentence_list) + 1, len(m) + 2) sub_pop.attron(self.colors_list['FILTER']) @@ -1038,6 +1038,8 @@ class _GlancesCurses(object): # self.term_window.keypad(0) return textbox.gather() + return None + def display_plugin(self, plugin_stats, display_optional=True, display_additional=True, max_y=65535, add_space=0): """Display the plugin_stats on the screen. @@ -1132,6 +1134,7 @@ class _GlancesCurses(object): # Have empty lines after the plugins self.next_line += add_space + return None def clear(self): """Erase the content of the screen. @@ -1214,8 +1217,7 @@ class _GlancesCurses(object): if isexitkey and self.args.help_tag: # Quit from help should return to main screen, not exit #1874 self.args.help_tag = not self.args.help_tag - isexitkey = False - return isexitkey + return False if not isexitkey and pressedkey > -1: # Redraw display diff --git a/glances/outputs/glances_sparklines.py b/glances/outputs/glances_sparklines.py index d4ada88c..99f6e9fe 100644 --- a/glances/outputs/glances_sparklines.py +++ b/glances/outputs/glances_sparklines.py @@ -59,6 +59,7 @@ class Sparkline(object): return self.__size if self.__display_value: return self.__size - 6 + return None @property def percents(self): diff --git a/glances/outputs/glances_stdout_apidoc.py b/glances/outputs/glances_stdout_apidoc.py index 907d4929..8b9350d9 100644 --- a/glances/outputs/glances_stdout_apidoc.py +++ b/glances/outputs/glances_stdout_apidoc.py @@ -82,8 +82,7 @@ def indent_stat(stat, indent=' '): if isinstance(stat, list) and len(stat) > 1 and isinstance(stat[0], dict): # Only display two first items return indent + pformat(stat[0:2]).replace('\n', '\n' + indent).replace("'", '"') - else: - return indent + pformat(stat).replace('\n', '\n' + indent).replace("'", '"') + return indent + pformat(stat).replace('\n', '\n' + indent).replace("'", '"') def print_api_status(): diff --git a/glances/outputs/glances_unicode.py b/glances/outputs/glances_unicode.py index 76ae3e60..99f4e786 100644 --- a/glances/outputs/glances_unicode.py +++ b/glances/outputs/glances_unicode.py @@ -25,5 +25,4 @@ def unicode_message(key, args=None): """Return the unicode message for the given key.""" if args and hasattr(args, 'disable_unicode') and args.disable_unicode: return _unicode_message[key][1] - else: - return _unicode_message[key][0] + return _unicode_message[key][0] diff --git a/glances/password.py b/glances/password.py index c4e8280e..9d79e995 100644 --- a/glances/password.py +++ b/glances/password.py @@ -38,8 +38,7 @@ class GlancesPassword(object): """ if self.config is None: return user_config_dir()[0] - else: - return self.config.get_value('passwords', 'local_password_path', default=user_config_dir()[0]) + return self.config.get_value('passwords', 'local_password_path', default=user_config_dir()[0]) @weak_lru_cache(maxsize=32) def get_hash(self, plain_password, salt=''): @@ -120,6 +119,4 @@ class GlancesPassword(object): """Load the hashed password from the Glances folder.""" # Read the password file, if it exists with open(self.password_file, 'r') as file_pwd: - hashed_password = file_pwd.read() - - return hashed_password + return file_pwd.read() diff --git a/glances/password_list.py b/glances/password_list.py index 21ee3c7a..1f3973fa 100644 --- a/glances/password_list.py +++ b/glances/password_list.py @@ -51,14 +51,14 @@ class GlancesPasswordList(GlancesPassword): """ if host is None: return self._password_dict - else: + + try: + return self._password_dict[host] + except (KeyError, TypeError): try: - return self._password_dict[host] + return self._password_dict['default'] except (KeyError, TypeError): - try: - return self._password_dict['default'] - except (KeyError, TypeError): - return None + return None def set_password(self, host, password): """Set a password for a specific host.""" diff --git a/glances/plugins/alert/__init__.py b/glances/plugins/alert/__init__.py index 8275bb30..4068d395 100644 --- a/glances/plugins/alert/__init__.py +++ b/glances/plugins/alert/__init__.py @@ -183,5 +183,4 @@ class PluginModel(GlancesPluginModel): """Compare a with b using the tolerance (if numerical).""" if str(int(a)).isdigit() and str(int(b)).isdigit(): return abs(a - b) <= max(abs(a), abs(b)) * tolerance - else: - return a == b + return a == b diff --git a/glances/plugins/amps/__init__.py b/glances/plugins/amps/__init__.py index 9e9e46be..acdcf315 100644 --- a/glances/plugins/amps/__init__.py +++ b/glances/plugins/amps/__init__.py @@ -93,13 +93,11 @@ class PluginModel(GlancesPluginModel): if nbprocess > 0: if int(countmin) <= int(nbprocess) <= int(countmax): return 'OK' - else: - return 'WARNING' - else: - if int(countmin) == 0: - return 'OK' - else: - return 'CRITICAL' + return 'WARNING' + + if int(countmin) == 0: + return 'OK' + return 'CRITICAL' def msg_curse(self, args=None, max_width=None): """Return the dict to display in the curse interface.""" diff --git a/glances/plugins/containers/__init__.py b/glances/plugins/containers/__init__.py index e88d1d36..024b97fa 100644 --- a/glances/plugins/containers/__init__.py +++ b/glances/plugins/containers/__init__.py @@ -164,8 +164,7 @@ class PluginModel(GlancesPluginModel): conf_podman_sock = self.get_conf_value('podman_sock') if len(conf_podman_sock) == 0: return "unix:///run/user/1000/podman/podman.sock" - else: - return conf_podman_sock[0] + return conf_podman_sock[0] def exit(self): """Overwrite the exit method to close threads.""" @@ -209,8 +208,7 @@ class PluginModel(GlancesPluginModel): all_tag = self.get_conf_value('all') if len(all_tag) == 0: return False - else: - return all_tag[0].lower() == 'true' + return all_tag[0].lower() == 'true' @GlancesPluginModel._check_decorator @GlancesPluginModel._log_result_decorator @@ -453,12 +451,11 @@ class PluginModel(GlancesPluginModel): """Analyse the container status.""" if status == 'running': return 'OK' - elif status == 'exited': + if status == 'exited': return 'WARNING' - elif status == 'dead': + if status == 'dead': return 'CRITICAL' - else: - return 'CAREFUL' + return 'CAREFUL' def sort_docker_stats(stats): diff --git a/glances/plugins/containers/engines/docker.py b/glances/plugins/containers/engines/docker.py index a74e2a70..ab27dadc 100644 --- a/glances/plugins/containers/engines/docker.py +++ b/glances/plugins/containers/engines/docker.py @@ -71,13 +71,12 @@ class DockerStatsFetcher: memory_stats = self._get_memory_stats() network_stats = self._get_network_stats() - computed_stats = { + return { "io": io_stats or {}, "memory": memory_stats or {}, "network": network_stats or {}, "cpu": cpu_stats or {"total": 0.0}, } - return computed_stats @property def time_since_update(self): diff --git a/glances/plugins/fs/__init__.py b/glances/plugins/fs/__init__.py index d5affe5b..49bb4f29 100644 --- a/glances/plugins/fs/__init__.py +++ b/glances/plugins/fs/__init__.py @@ -216,8 +216,7 @@ class PluginModel(GlancesPluginModel): # Do not take hidden file system into account if self.is_hide(fs_current['mnt_point']): continue - else: - stats.append(fs_current) + stats.append(fs_current) else: # Default behavior for fs in fs_stat: @@ -232,8 +231,7 @@ class PluginModel(GlancesPluginModel): # Do not take hidden file system into account if self.is_hide(fs_current['mnt_point']) or self.is_hide(fs_current['device_name']): continue - else: - stats.append(fs_current) + stats.append(fs_current) # Update the stats self.stats = stats diff --git a/glances/plugins/gpu/cards/amd.py b/glances/plugins/gpu/cards/amd.py index 2f8cd562..2223fae4 100644 --- a/glances/plugins/gpu/cards/amd.py +++ b/glances/plugins/gpu/cards/amd.py @@ -37,6 +37,7 @@ See: https://wiki.archlinux.org/title/AMDGPU#Manually import os import re +from typing import Optional DRM_ROOT_FOLDER: str = '/sys/class/drm' CARD_REGEX: str = r"^card\d$" @@ -104,7 +105,7 @@ def get_device_name(device_folder: str) -> str: return 'AMD GPU' -def get_mem(device_folder: str) -> int: +def get_mem(device_folder: str) -> Optional[int]: """Return the memory consumption in %.""" mem_info_vram_total = os.path.join(device_folder, GPU_MEM_TOTAL) mem_info_vram_used = os.path.join(device_folder, GPU_MEM_USED) @@ -118,7 +119,7 @@ def get_mem(device_folder: str) -> int: return None -def get_proc(device_folder: str) -> int: +def get_proc(device_folder: str) -> Optional[int]: """Return the processor consumption in %.""" gpu_busy_percent = os.path.join(device_folder, GPU_PROC_PERCENT) if os.path.isfile(gpu_busy_percent): @@ -127,7 +128,7 @@ def get_proc(device_folder: str) -> int: return None -def get_temperature(device_folder: str) -> int: +def get_temperature(device_folder: str) -> Optional[int]: """Return the processor temperature in °C (mean of all HWMON)""" temp_input = [] for root, dirs, _ in os.walk(device_folder): @@ -140,10 +141,9 @@ def get_temperature(device_folder: str) -> int: temp_input.append(int(f.read())) if len(temp_input) > 0: return round(sum(temp_input) / len(temp_input) / 1000) - else: - return None + return None -def get_fan_speed(device_folder: str) -> int: +def get_fan_speed(device_folder: str) -> Optional[int]: """Return the fan speed in %.""" return None diff --git a/glances/plugins/load/__init__.py b/glances/plugins/load/__init__.py index c26446bc..9c3c81bc 100644 --- a/glances/plugins/load/__init__.py +++ b/glances/plugins/load/__init__.py @@ -111,8 +111,7 @@ class PluginModel(GlancesPluginModel): stats = self.get_stats_snmp(snmp_oid=snmp_oid) if stats['min1'] == '': - stats = self.get_init_value() - return stats + return self.get_init_value() # Python 3 return a dict like: # {'min1': "b'0.08'", 'min5': "b'0.12'", 'min15': "b'0.15'"} @@ -206,5 +205,4 @@ def get_load_average(percent: bool = False): if load_average and percent: return tuple([round(i / get_nb_log_core() * 100, 1) for i in load_average]) - else: - return load_average + return load_average diff --git a/glances/plugins/plugin/model.py b/glances/plugins/plugin/model.py index 42973918..9e40fce1 100644 --- a/glances/plugins/plugin/model.py +++ b/glances/plugins/plugin/model.py @@ -151,7 +151,7 @@ class GlancesPluginModel(object): def get_key(self): """Return the key of the list.""" - return None + return def is_enabled(self, plugin_name=None): """Return true if plugin is enabled.""" @@ -227,11 +227,9 @@ class GlancesPluginModel(object): s = self.stats_history.get(nb=nb) if item is None: return s - else: - if item in s: - return s[item] - else: - return None + if item in s: + return s[item] + return None def get_export_history(self, item=None): """Return the stats history object to export.""" @@ -410,14 +408,14 @@ class GlancesPluginModel(object): """ if not isinstance(self.get_raw(), list): return None - else: - if (not isinstance(value, int) and not isinstance(value, float)) and value.isdigit(): - value = int(value) - try: - return {value: [i for i in self.get_raw() if i[item] == value]} - except (KeyError, ValueError) as e: - logger.error("Cannot get item({})=value({}) ({})".format(item, value, e)) - return None + + if (not isinstance(value, int) and not isinstance(value, float)) and value.isdigit(): + value = int(value) + try: + return {value: [i for i in self.get_raw() if i[item] == value]} + except (KeyError, ValueError) as e: + logger.error("Cannot get item({})=value({}) ({})".format(item, value, e)) + return None def get_stats_value(self, item, value): """Return the stats object for a specific item=value in JSON format. @@ -427,15 +425,13 @@ class GlancesPluginModel(object): rsv = self.get_raw_stats_value(item, value) if rsv is None: return None - else: - return json_dumps(rsv) + return json_dumps(rsv) def get_item_info(self, item, key, default=None): """Return the item info grabbed into self.fields_description.""" if self.fields_description is None or item not in self.fields_description: return default - else: - return self.fields_description[item].get(key, default) + return self.fields_description[item].get(key, default) def update_views_hidden(self): """Update the hidden views @@ -553,14 +549,11 @@ class GlancesPluginModel(object): if key is None: return item_views - else: - if option is None: - return item_views[key] - else: - if option in item_views[key]: - return item_views[key][option] - else: - return 'DEFAULT' + if option is None: + return item_views[key] + if option in item_views[key]: + return item_views[key][option] + return 'DEFAULT' def get_json_views(self, item=None, key=None, option=None): """Return the views (in JSON).""" @@ -626,8 +619,7 @@ class GlancesPluginModel(object): """Return the limits object.""" if item is None: return self._limits - else: - return self._limits.get('{}_{}'.format(self.plugin_name, item), None) + return self._limits.get('{}_{}'.format(self.plugin_name, item), None) def get_stats_action(self): """Return stats for the action. @@ -742,12 +734,11 @@ class GlancesPluginModel(object): """Filter the stats to keep only the fields we want (the one defined in fields_description).""" if hasattr(stats, '_asdict'): return {k: v for k, v in stats._asdict().items() if k in self.fields_description} - elif isinstance(stats, dict): + if isinstance(stats, dict): return {k: v for k, v in stats.items() if k in self.fields_description} - elif isinstance(stats, list): + if isinstance(stats, list): return [self.filter_stats(s) for s in stats] - else: - return stats + return stats def manage_threshold(self, stat_name, trigger): """Manage the threshold for the current stat.""" @@ -793,8 +784,7 @@ class GlancesPluginModel(object): """Return true if the criticality limit exist for the given stat_name""" if stat_name == "": return self.plugin_name + '_' + criticality in self._limits - else: - return stat_name + '_' + criticality in self._limits + return stat_name + '_' + criticality in self._limits def get_limit(self, criticality=None, stat_name=""): """Return the limit value for the given criticality. @@ -806,7 +796,7 @@ class GlancesPluginModel(object): # Example: network_wlan0_rx_careful if stat_name + '_' + criticality in self._limits: return self._limits[stat_name + '_' + criticality] - elif self.plugin_name + '_' + criticality in self._limits: + if self.plugin_name + '_' + criticality in self._limits: return self._limits[self.plugin_name + '_' + criticality] # No key found, the raise an error @@ -840,10 +830,9 @@ class GlancesPluginModel(object): # Example: network_wlan0_rx_log if stat_name + '_log' in self._limits: return self._limits[stat_name + '_log'][0].lower() == 'true' - elif self.plugin_name + '_log' in self._limits: + if self.plugin_name + '_log' in self._limits: return self._limits[self.plugin_name + '_log'][0].lower() == 'true' - else: - return default_action + return default_action def get_conf_value(self, value, header="", plugin_name=None, default=[]): """Return the configuration (header_) value for the current plugin. @@ -895,14 +884,12 @@ class GlancesPluginModel(object): """Return True if the value should be displayed in the UI""" if self.get_conf_value('show', header=header) != []: return self.is_show(value, header=header) - else: - return not self.is_hide(value, header=header) + return not self.is_hide(value, header=header) def read_alias(self): if self.plugin_name + '_' + 'alias' in self._limits: return {i.split(':')[0].lower(): i.split(':')[1] for i in self._limits[self.plugin_name + '_' + 'alias']} - else: - return dict() + return dict() def has_alias(self, header): """Return the alias name for the relative header it it exists otherwise None.""" diff --git a/glances/plugins/ports/__init__.py b/glances/plugins/ports/__init__.py index 87c467fc..78e58347 100644 --- a/glances/plugins/ports/__init__.py +++ b/glances/plugins/ports/__init__.py @@ -313,8 +313,7 @@ class ThreadScanner(threading.Thread): """Scan the port structure (dict) and update the status key.""" if int(port['port']) == 0: return self._port_scan_icmp(port) - else: - return self._port_scan_tcp(port) + return self._port_scan_tcp(port) def _resolv_name(self, hostname): """Convert hostname to IP address.""" diff --git a/glances/plugins/processlist/__init__.py b/glances/plugins/processlist/__init__.py index b2a4bf2f..fab3e12b 100644 --- a/glances/plugins/processlist/__init__.py +++ b/glances/plugins/processlist/__init__.py @@ -835,8 +835,7 @@ class PluginModel(GlancesPluginModel): """Return the decoration string for the current mmm status.""" if mmm is not None: return 'DEFAULT' - else: - return 'FILTER' + return 'FILTER' def __mmm_reset(self): """Reset the MMM stats.""" @@ -902,6 +901,6 @@ class PluginModel(GlancesPluginModel): """Return the maximum PID size in number of char.""" if self.pid_max is not None: return len(str(self.pid_max)) - else: - # By default return 5 (corresponding to 99999 PID number) - return 5 + + # By default return 5 (corresponding to 99999 PID number) + return 5 diff --git a/glances/plugins/raid/__init__.py b/glances/plugins/raid/__init__.py index 2145a169..c9fcdf7f 100644 --- a/glances/plugins/raid/__init__.py +++ b/glances/plugins/raid/__init__.py @@ -161,6 +161,6 @@ class PluginModel(GlancesPluginModel): return 'CRITICAL' if used is None or available is None: return 'DEFAULT' - elif used < available: + if used < available: return 'WARNING' return 'OK' diff --git a/glances/plugins/sensors/__init__.py b/glances/plugins/sensors/__init__.py index cb11acde..4eb1f116 100644 --- a/glances/plugins/sensors/__init__.py +++ b/glances/plugins/sensors/__init__.py @@ -153,8 +153,7 @@ class PluginModel(GlancesPluginModel): # Remove duplicates thanks to https://stackoverflow.com/a/9427216/1919431 stats_transformed = [dict(t) for t in {tuple(d.items()) for d in stats_transformed}] # Sort by label - stats_transformed = sorted(stats_transformed, key=lambda d: d['label']) - return stats_transformed + return sorted(stats_transformed, key=lambda d: d['label']) @GlancesPluginModel._check_decorator @GlancesPluginModel._log_result_decorator @@ -191,10 +190,9 @@ class PluginModel(GlancesPluginModel): # Get the alias for each stat if self.has_alias(stats["label"].lower()): return self.has_alias(stats["label"].lower()) - elif self.has_alias("{}_{}".format(stats["label"], stats["type"]).lower()): + if self.has_alias("{}_{}".format(stats["label"], stats["type"]).lower()): return self.has_alias("{}_{}".format(stats["label"], stats["type"]).lower()) - else: - return stats["label"] + return stats["label"] def __set_type(self, stats, sensor_type): """Set the plugin type. @@ -254,9 +252,9 @@ class PluginModel(GlancesPluginModel): return '' if stats['status'].startswith('Charg'): return unicode_message('ARROW_UP') - elif stats['status'].startswith('Discharg'): + if stats['status'].startswith('Discharg'): return unicode_message('ARROW_DOWN') - elif stats['status'].startswith('Full'): + if stats['status'].startswith('Full'): return unicode_message('CHECK') return '' diff --git a/glances/plugins/uptime/__init__.py b/glances/plugins/uptime/__init__.py index 06283711..0e3f71eb 100644 --- a/glances/plugins/uptime/__init__.py +++ b/glances/plugins/uptime/__init__.py @@ -83,6 +83,4 @@ class PluginModel(GlancesPluginModel): if not self.stats or self.is_disabled(): return ret - ret = [self.curse_add_line('Uptime: {}'.format(self.stats))] - - return ret + return [self.curse_add_line('Uptime: {}'.format(self.stats))] diff --git a/glances/processes.py b/glances/processes.py index c93944a6..fea4c004 100644 --- a/glances/processes.py +++ b/glances/processes.py @@ -568,8 +568,7 @@ class GlancesProcesses(object): If as_programs is True, return the list of programs.""" if as_programs: return processes_to_programs(self.processlist) - else: - return self.processlist + return self.processlist def get_export(self): """Return the processlist for export.""" diff --git a/glances/secure.py b/glances/secure.py index 30f13803..03745d3a 100644 --- a/glances/secure.py +++ b/glances/secure.py @@ -40,7 +40,7 @@ def __secure_popen(cmd): cmd_split_redirect = cmd.split('>') if len(cmd_split_redirect) > 2: return 'Glances error: Only one file redirection allowed ({})'.format(cmd) - elif len(cmd_split_redirect) == 2: + if len(cmd_split_redirect) == 2: stdout_redirect = cmd_split_redirect[1].strip() cmd = cmd_split_redirect[0] else: diff --git a/glances/server.py b/glances/server.py index 55f6139f..55b48831 100644 --- a/glances/server.py +++ b/glances/server.py @@ -68,17 +68,15 @@ class GlancesXMLRPCHandler(SimpleXMLRPCRequestHandler, object): # TODO: config is not taken into account: it may be a problem ? pwd = GlancesPassword(username=username, config=None) return pwd.check_password(self.server.user_dict[username], password) - else: - return False + return False def parse_request(self): if SimpleXMLRPCRequestHandler.parse_request(self): # Next we authenticate if self.authenticate(self.headers): return True - else: - # if authentication fails, tell the client - self.send_error(401, 'Authentication failed') + # if authentication fails, tell the client + self.send_error(401, 'Authentication failed') return False def log_message(self, log_format, *args): diff --git a/glances/stats.py b/glances/stats.py index 8722e31e..0f55990f 100644 --- a/glances/stats.py +++ b/glances/stats.py @@ -55,10 +55,9 @@ class GlancesStats(object): if hasattr(plugin, 'get_json_views'): # The method get_views exist, return it return getattr(plugin, 'get_json_views') - else: - # The method get_views is not found for the plugin - raise AttributeError(item) - elif item.startswith('get'): + # The method get_views is not found for the plugin + raise AttributeError(item) + if item.startswith('get'): # Get the plugin name plugname = item[len('get') :].lower() # Get the plugin instance @@ -66,12 +65,10 @@ class GlancesStats(object): if hasattr(plugin, 'get_stats'): # The method get_stats exist, return it return getattr(plugin, 'get_stats') - else: - # The method get_stats is not found for the plugin - raise AttributeError(item) - else: - # Default behavior + # The method get_stats is not found for the plugin raise AttributeError(item) + # Default behavior + raise AttributeError(item) def load_modules(self, args): """Wrapper to load: plugins and export modules.""" @@ -237,8 +234,7 @@ class GlancesStats(object): """ if enable: return [p for p in self._plugins if self._plugins[p].is_enabled()] - else: - return [p for p in self._plugins] + return [p for p in self._plugins] def getExportsList(self, enable=True): """Return the exports list. @@ -250,8 +246,7 @@ class GlancesStats(object): """ if enable: return [e for e in self._exports] - else: - return [e for e in self._exports_all] + return [e for e in self._exports_all] def load_limits(self, config=None): """Load the stats limits (except the one in the exclude list).""" @@ -367,8 +362,7 @@ class GlancesStats(object): """Return the plugin name.""" if plugin_name in self._plugins: return self._plugins[plugin_name] - else: - return None + return None def end(self): """End of the Glances stats.""" diff --git a/glances/thresholds.py b/glances/thresholds.py index 9c352831..a7624450 100644 --- a/glances/thresholds.py +++ b/glances/thresholds.py @@ -38,18 +38,17 @@ class GlancesThresholds(object): if stat_name in self._thresholds: return self._thresholds[stat_name] - else: - return {} + return {} def add(self, stat_name, threshold_description): """Add a new threshold to the dict (key = stat_name)""" if threshold_description not in self.threshold_list: return False - else: - self._thresholds[stat_name] = getattr( - self.current_module, 'GlancesThreshold' + threshold_description.capitalize() - )() - return True + + self._thresholds[stat_name] = getattr( + self.current_module, 'GlancesThreshold' + threshold_description.capitalize() + )() + return True # Global variable uses to share thresholds between Glances components diff --git a/pyproject.toml b/pyproject.toml index 5b6464c3..61ed8c3e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -21,7 +21,7 @@ select = [ "W", # pycodestyle # "UP", # pyupgrde # "C4", # flake8-comprehensions -# "RET", # flake8-return + "RET", # flake8-return # "FBT", # flake8-boolean-trap # "RUF", # Ruff-specific rules # "PERF", # Perflint diff --git a/setup.py b/setup.py index 2c7ea8d7..e220b2f6 100755 --- a/setup.py +++ b/setup.py @@ -31,7 +31,7 @@ with open('README.rst', encoding='utf-8') as f: def get_data_files(): - data_files = [ + return [ ( 'share/doc/glances', ['AUTHORS', 'COPYING', 'NEWS.rst', 'README.rst', "SECURITY.md", 'CONTRIBUTING.md', 'conf/glances.conf'], @@ -39,8 +39,6 @@ def get_data_files(): ('share/man/man1', ['docs/man/glances.1']), ] - return data_files - with open('requirements.txt') as f: required = f.read().splitlines()