From 63723baf077c1e0860a7774babe2c0356f8a05cd Mon Sep 17 00:00:00 2001 From: Matthias Urlichs Date: Mon, 28 Jan 2019 21:07:04 +0100 Subject: [PATCH] list()-ify map() and filter() where required. At some places it's not. --- src/octoprint/__init__.py | 2 +- src/octoprint/access/groups.py | 6 +++--- src/octoprint/access/permissions.py | 4 ++-- src/octoprint/access/users.py | 4 ++-- src/octoprint/events.py | 2 +- src/octoprint/plugin/core.py | 10 +++++----- .../plugins/announcements/__init__.py | 4 ++-- src/octoprint/plugins/appkeys/__init__.py | 19 +++++++++++-------- src/octoprint/plugins/backup/__init__.py | 2 +- .../plugins/pluginmanager/__init__.py | 2 +- .../plugins/softwareupdate/__init__.py | 6 +++--- .../scripts/update-octoprint.py | 12 ++++++------ src/octoprint/printer/standard.py | 2 +- src/octoprint/server/api/__init__.py | 4 ++-- src/octoprint/server/api/access.py | 4 ++-- src/octoprint/server/api/files.py | 4 ++-- src/octoprint/server/api/languages.py | 2 +- src/octoprint/server/util/flask.py | 2 +- src/octoprint/server/util/tornado.py | 4 ++-- src/octoprint/server/util/watchdog.py | 2 +- src/octoprint/util/__init__.py | 12 ++++++++++-- versioneer.py | 4 ++-- 22 files changed, 62 insertions(+), 51 deletions(-) diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index d41fbdfc9..b88d9065e 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -449,7 +449,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None): def format_blacklist(entries): format_entry = lambda x: "{} ({})".format(x[0], x[1]) if isinstance(x, (list, tuple)) and len(x) == 2 \ else "{} (any)".format(x) - return ", ".join(list(map(format_entry, entries))) + return ", ".join(map(format_entry, entries)) def process_blacklist(entries): result = [] diff --git a/src/octoprint/access/groups.py b/src/octoprint/access/groups.py index a1470e7ed..1f9353a0b 100644 --- a/src/octoprint/access/groups.py +++ b/src/octoprint/access/groups.py @@ -129,8 +129,8 @@ class GroupManager(object): return None def _to_permissions(self, *permissions): - return filter(lambda x: x is not None, - [Permissions.find(permission) for permission in permissions]) + return list(filter(lambda x: x is not None, + [Permissions.find(permission) for permission in permissions])) def _from_permissions(self, *permissions): return [permission.key for permission in permissions] @@ -469,7 +469,7 @@ class Group(object): if Permissions.ADMIN in self._permissions: return Permissions.all() - return filter(lambda p: p is not None, self._permissions) + return list(filter(lambda p: p is not None, self._permissions)) @property def needs(self): diff --git a/src/octoprint/access/permissions.py b/src/octoprint/access/permissions.py index 2dab4785e..9075da118 100644 --- a/src/octoprint/access/permissions.py +++ b/src/octoprint/access/permissions.py @@ -102,7 +102,7 @@ class OctoPrintPermission(Permission): return '{}({!r}, {!r}, {})'.format(self.__class__.__name__, self.get_name(), self.get_description(), - ', '.join(list(map(repr, self.needs)))) + ', '.join(map(repr, self.needs))) def __hash__(self): return self.get_name().__hash__() @@ -220,7 +220,7 @@ class PermissionsMetaClass(type): return cls.permissions.values() def filter(cls, cb): - return filter(cb, cls.all()) + return list(filter(cb, cls.all())) def find(cls, p, filter=None): key = None diff --git a/src/octoprint/access/users.py b/src/octoprint/access/users.py index 6b67d692c..8bcf0cbc6 100644 --- a/src/octoprint/access/users.py +++ b/src/octoprint/access/users.py @@ -516,7 +516,7 @@ class FilebasedUserManager(UserManager): return [self._group_manager.user_group] def _refresh_groups(self, user): - user._groups = self._to_groups(*list(map(lambda g: g.key, user.groups))) + user._groups = self._to_groups(*map(lambda g: g.key, user.groups)) def add_user(self, username, password, active=False, permissions=None, groups=None, apikey=None, overwrite=False): if not permissions: @@ -1042,7 +1042,7 @@ class User(UserMixin): if Permissions.ADMIN in self._permissions: return Permissions.all() - return filter(lambda p: p is not None, self._permissions) + return list(filter(lambda p: p is not None, self._permissions)) @property def groups(self): diff --git a/src/octoprint/events.py b/src/octoprint/events.py index 1d51115f9..e6a57f259 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -302,7 +302,7 @@ class DebugEventListener(GenericEventListener): def __init__(self): GenericEventListener.__init__(self) - events = filter(lambda x: not x.startswith("__"), dir(Events)) + events = list(filter(lambda x: not x.startswith("__"), dir(Events))) self.subscribe(events) def eventCallback(self, event, payload): diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index 0775083c9..88eabecc8 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -516,8 +516,8 @@ class PluginInfo(object): with io.open(path, 'rb') as f: root = ast.parse(f.read()) - assignments = filter(lambda x: isinstance(x, ast.Assign) and x.targets, - root.body) + assignments = list(filter(lambda x: isinstance(x, ast.Assign) and x.targets, + root.body)) def extract_target_ids(node): return list(map(lambda x: x.id, @@ -1188,7 +1188,7 @@ class PluginManager(object): if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)): hooks = hooks[0] - hooks = filter(lambda hook: hook is not None, hooks) + hooks = list(filter(lambda hook: hook is not None, hooks)) if not hooks: return False if not plugin or not plugin.hooks: @@ -1222,7 +1222,7 @@ class PluginManager(object): if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)): hooks = hooks[0] - hooks = filter(lambda hook: hook is not None, hooks) + hooks = list(filter(lambda hook: hook is not None, hooks)) if not hooks: return False if not hook: @@ -1260,7 +1260,7 @@ class PluginManager(object): if mixins and len(mixins) == 1 and isinstance(mixins[0], (list, tuple)): mixins = mixins[0] - mixins = filter(lambda mixin: mixin is not None, mixins) + mixins = list(filter(lambda mixin: mixin is not None, mixins)) if not mixins: return False if not plugin or not plugin.implementation: diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py index 161992120..f2ab0c93c 100644 --- a/src/octoprint/plugins/announcements/__init__.py +++ b/src/octoprint/plugins/announcements/__init__.py @@ -22,7 +22,7 @@ from collections import OrderedDict from octoprint.access.permissions import Permissions from octoprint.server.util.flask import no_firstrun_access, with_revalidation_checking, check_etag -from octoprint.util import utmify +from octoprint.util import utmify, count from flask_babel import gettext from octoprint import __version__ as OCTOPRINT_VERSION @@ -170,7 +170,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, for key, data in channel_configs.items(): read_until = channel_configs[key].get("read_until", None) entries = sorted(self._to_internal_feed(channel_data.get(key, []), read_until=read_until), key=lambda e: e["published"], reverse=True) - unread = len(list(filter(lambda e: not e["read"], entries))) + unread = count(filter(lambda e: not e["read"], entries)) if read_until is None and entries: last = entries[0]["published"] diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py index 8b2e5301c..05efe9aa9 100644 --- a/src/octoprint/plugins/appkeys/__init__.py +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -197,7 +197,7 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin, else: keys = self._api_keys_for_user(user_id) - return flask.jsonify(keys=map(lambda x: x.external(), keys), + return flask.jsonify(keys=list(map(lambda x: x.external(), keys)), pending=dict((x.user_token, x.external()) for x in self._get_pending_by_user_id(user_id))) def on_api_command(self, command, data): @@ -266,7 +266,8 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin, def _expire_pending(self, user_token): with self._pending_lock: len_before = len(self._pending_decisions) - self._pending_decisions = filter(lambda x: x.user_token != user_token, self._pending_decisions) + self._pending_decisions = list(filter(lambda x: x.user_token != user_token, + self._pending_decisions)) len_after = len(self._pending_decisions) if len_after < len_before: @@ -279,8 +280,8 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin, with self._pending_lock: cutoff = monotonic_time() - CUTOFF_TIME len_before = len(self._pending_decisions) - self._pending_decisions = filter(lambda x: x.created >= cutoff, - self._pending_decisions) + self._pending_decisions = list(filter(lambda x: x.created >= cutoff, + self._pending_decisions)) len_after = len(self._pending_decisions) if len_after < len_before: self._logger.info("Deleted {} stale pending authorization requests".format(len_before - len_after)) @@ -300,7 +301,8 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin, self._ready_decisions.append(ReadyDecision.for_pending(pending, user_id)) with self._pending_lock: - self._pending_decisions = filter(lambda x: x.user_token != user_token, self._pending_decisions) + self._pending_decisions = list(filter(lambda x: x.user_token != user_token, + self._pending_decisions)) return True @@ -318,7 +320,8 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin, api_key = self._add_api_key(decision.user_id, decision.app_id) with self._ready_lock: - self._ready_decisions = filter(lambda x: x.app_token != app_token, self._ready_decisions) + self._ready_decisions = list(filter(lambda x: x.app_token != app_token, + self._ready_decisions)) return api_key @@ -336,13 +339,13 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin, def _delete_api_key(self, api_key): with self._keys_lock: for user_id, data in self._keys.items(): - self._keys[user_id] = filter(lambda x: x.api_key != api_key, data) + self._keys[user_id] = list(filter(lambda x: x.api_key != api_key, data)) self._save_keys() def _user_for_api_key(self, api_key): with self._keys_lock: for user_id, data in self._keys.items(): - if filter(lambda x: x.api_key == api_key, data): + if any(filter(lambda x: x.api_key == api_key, data)): return self._user_manager.findUser(userid=user_id) return None diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index 3a11e3ce4..6a382f2fc 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -492,7 +492,7 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, assert all(map(lambda x: isinstance(x, dict) and "key" in x and "name" in x and "url" in x, unknown_plugins)) installed_plugins = self._plugin_manager.plugins - unknown_plugins = filter(lambda x: x["key"] not in installed_plugins, unknown_plugins) + unknown_plugins = list(filter(lambda x: x["key"] not in installed_plugins, unknown_plugins)) if not unknown_plugins: # no plugins left uninstalled, delete data file try: diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 0f2814ef7..4b2598631 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -834,7 +834,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if repo_data is None: return False - self._repository_plugins = map(map_repository_entry, repo_data) + self._repository_plugins = list(map(map_repository_entry, repo_data)) return True def _fetch_notices_from_disk(self): diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index d2d8a538e..1cd8c431a 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -521,7 +521,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, @Permissions.PLUGIN_SOFTWAREUPDATE_CHECK.require(403) def check_for_update(self): if "check" in flask.request.values: - check_targets = map(lambda x: x.strip(), flask.request.values["check"].split(",")) + check_targets = list(map(lambda x: x.strip(), flask.request.values["check"].split(","))) else: check_targets = None @@ -602,7 +602,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, return flask.make_response("Invalid JSON", 400) if "targets" in json_data: - targets = map(lambda x: x.strip(), json_data["targets"]) + targets = list(map(lambda x: x.strip(), json_data["targets"])) else: targets = None @@ -1146,7 +1146,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, def _log(self, lines, prefix=None, stream=None, strip=True): if strip: - lines = map(lambda x: x.strip(), lines) + lines = list(map(lambda x: x.strip(), lines)) self._send_client_message("loglines", data=dict(loglines=[dict(line=line, stream=stream) for line in lines])) for line in lines: diff --git a/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py b/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py index 38dc20ad4..7a441aec3 100644 --- a/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py +++ b/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py @@ -97,28 +97,28 @@ def _execute(command, **kwargs): while p.commands[0].poll() is None: lines = p.stderr.readlines(timeout=0.5) if lines: - lines = map(lambda x: _to_unicode(x, errors="replace"), lines) + lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines)) _log_stderr(*lines) - all_stderr += list(lines) + all_stderr += lines lines = p.stdout.readlines(timeout=0.5) if lines: - lines = map(lambda x: _to_unicode(x, errors="replace"), lines) + lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines)) _log_stdout(*lines) - all_stdout += list(lines) + all_stdout += lines finally: p.close() lines = p.stderr.readlines() if lines: - lines = map(lambda x: _to_unicode(x, errors="replace"), lines) + lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines)) _log_stderr(*lines) all_stderr += lines lines = p.stdout.readlines() if lines: - lines = map(lambda x: _to_unicode(x, errors="replace"), lines) + lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines)) _log_stdout(*lines) all_stdout += lines diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index 7c7f05ea5..6e3448a0e 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -719,7 +719,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): def _get_free_remote_name(self, filename): self.refresh_sd_files(blocking=True) - existingSdFiles = map(lambda x: x[0], self._comm.getSdFiles()) + existingSdFiles = list(map(lambda x: x[0], self._comm.getSdFiles())) if valid_file_type(filename, "gcode"): # figure out remote filename diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index 75b852e03..457a9b8e3 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -430,11 +430,11 @@ def _test_url(data): if "content_type_whitelist" in data: if not isinstance(data["content_type_whitelist"], (list, tuple)): return make_response("content_type_whitelist must be a list of mime types") - content_type_whitelist = map(util.parse_mime_type, data["content_type_whitelist"]) + content_type_whitelist = list(map(util.parse_mime_type, data["content_type_whitelist"])) if "content_type_blacklist" in data: if not isinstance(data["content_type_whitelist"], (list, tuple)): return make_response("content_type_blacklist must be a list of mime types") - content_type_blacklist = map(util.parse_mime_type, data["content_type_blacklist"]) + content_type_blacklist = list(map(util.parse_mime_type, data["content_type_blacklist"])) response_result = None outcome = True diff --git a/src/octoprint/server/api/access.py b/src/octoprint/server/api/access.py index d30666c7f..cb147a806 100644 --- a/src/octoprint/server/api/access.py +++ b/src/octoprint/server/api/access.py @@ -341,7 +341,7 @@ def generate_apikey_for_user(username): return make_response(("Forbidden", 403, [])) def _to_external_permissions(*permissions): - return map(lambda p: p.get_name(), permissions) + return list(map(lambda p: p.get_name(), permissions)) def _to_external_groups(*groups): - return map(lambda g: g.get_name(), groups) + return list(map(lambda g: g.get_name(), groups)) diff --git a/src/octoprint/server/api/files.py b/src/octoprint/server/api/files.py index c7661860d..077f4f656 100644 --- a/src/octoprint/server/api/files.py +++ b/src/octoprint/server/api/files.py @@ -49,7 +49,7 @@ def _create_lastmodified(path, recursive): logging.getLogger(__name__).exception("There was an error retrieving the last modified data from storage {}".format(storage)) lms.append(None) - if filter(lambda x: x is None, lms): + if any(filter(lambda x: x is None, lms)): # we return None if ANY of the involved storages returned None return None @@ -251,7 +251,7 @@ def _getFileList(origin, path=None, filter=None, recursive=False, allow_from_cac def _verifyFileExists(origin, filename): if origin == FileDestinations.SDCARD: - return filename in map(lambda x: x[0], printer.get_sd_files()) + return filename in (x[0] for x in printer.get_sd_files()) else: return fileManager.file_exists(origin, filename) diff --git a/src/octoprint/server/api/languages.py b/src/octoprint/server/api/languages.py index c303cc153..0bac32356 100644 --- a/src/octoprint/server/api/languages.py +++ b/src/octoprint/server/api/languages.py @@ -100,7 +100,7 @@ def uploadLanguagePack(): upload_name = request.values[input_upload_name] upload_path = request.values[input_upload_path] - exts = list(filter(lambda x: upload_name.lower().endswith(x), (".zip", ".tar.gz", ".tgz", ".tar"))) + exts = filter(lambda x: upload_name.lower().endswith(x), (".zip", ".tar.gz", ".tgz", ".tar")) if not len(exts): return make_response("File doesn't have a valid extension for a language pack archive", 400) diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index 05573e7de..76df556c0 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -76,7 +76,7 @@ def enable_additional_translations(default_locale="en", additional_folders=None) locale_dir = os.path.join(entry.path, 'LC_MESSAGES') if not os.path.isdir(locale_dir): continue - if filter(lambda x: x.name.endswith('.mo'), scandir(locale_dir)): + if len(list(filter(lambda x: x.name.endswith('.mo'), scandir(locale_dir)))): result.append(Locale.parse(entry.name)) return result diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index 18a36dc83..4a663c3dc 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -776,7 +776,7 @@ class CustomHTTP1Connection(tornado.http1connection.HTTP1Connection): tornado.http1connection.HTTP1Connection.__init__(self, stream, is_client, params=params, context=context) import re - self._max_body_sizes = map(lambda x: (x[0], re.compile(x[1]), x[2]), self.params.max_body_sizes or list()) + self._max_body_sizes = list(map(lambda x: (x[0], re.compile(x[1]), x[2]), self.params.max_body_sizes or list())) self._default_max_body_size = self.params.default_max_body_size or self.stream.max_buffer_size def _read_body(self, code, headers, delegate): @@ -1058,7 +1058,7 @@ class UrlProxyHandler(RequestlessExceptionLoggingMixin, tornado.web.RequestHandl if not self._basename: return None - typeValue = map(str.strip, content_type.split(";")) + typeValue = list(map(str.strip, content_type.split(";"))) if len(typeValue) == 0: return None diff --git a/src/octoprint/server/util/watchdog.py b/src/octoprint/server/util/watchdog.py index a1335804a..9de62d85c 100644 --- a/src/octoprint/server/util/watchdog.py +++ b/src/octoprint/server/util/watchdog.py @@ -23,7 +23,7 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler): """ def __init__(self, file_manager, printer): - watchdog.events.PatternMatchingEventHandler.__init__(self, patterns=map(lambda x: "*.%s" % x, octoprint.filemanager.get_all_extensions())) + watchdog.events.PatternMatchingEventHandler.__init__(self, patterns=list(map(lambda x: "*.%s" % x, octoprint.filemanager.get_all_extensions()))) self._logger = logging.getLogger(__name__) diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index b2e94b48d..608a122aa 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -439,7 +439,7 @@ def find_collision_free_name(filename, extension, existing_filenames, max_power= existing_filenames = [to_unicode(x[1:] if x.startswith("/") else x) for x in existing_filenames] def make_valid(text): - return re.sub(u"\s+", u"_", text.translate({ord(i):None for i in ".\"/\\[]:;=,"})).lower() + return re.sub(r"\\s+", "_", text.translate({ord(i):None for i in ".\"/\\[]:;=,"})).lower() filename = make_valid(filename) extension = make_valid(extension) @@ -1671,4 +1671,12 @@ class CaseInsensitiveSet(collections.Set): # originally from https://stackoverflow.com/a/5967539 def natural_key(text): - return [ int(c) if c.isdigit() else c for c in re.split("(\d+)", text) ] + return [ int(c) if c.isdigit() else c for c in re.split(r"(\d+)", text) ] + + +# len(generator) doesn#t work +def count(gen): + n = 0 + for _ in gen: + n += 1 + return n diff --git a/versioneer.py b/versioneer.py index 3d22de91f..e7dd18599 100644 --- a/versioneer.py +++ b/versioneer.py @@ -817,7 +817,7 @@ def git_parse_lookup_file(path): continue try: - split_line = map(lambda x: x.strip(), line.split()) + split_line = list(map(lambda x: x.strip(), line.split())) if not len(split_line): continue @@ -1389,7 +1389,7 @@ def git_parse_lookup_file(path): continue try: - split_line = map(lambda x: x.strip(), line.split()) + split_line = list(map(lambda x: x.strip(), line.split())) if not len(split_line): continue