list()-ify map() and filter()

where required. At some places it's not.
This commit is contained in:
Matthias Urlichs committed 2019-01-28 21:55:44 +01:00
1 parent b60b20d784
commit 63723baf07
22 files changed
+62 -51

No files matched your search

+1 -1
View File
@@ -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 = []
+3 -3
View File
@@ -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):
+2 -2
View File
@@ -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
+2 -2
View File
@@ -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):
+1 -1
View File
@@ -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):
+5 -5
View File
@@ -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:
@@ -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"]
+11 -8
View File
@@ -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
+1 -1
View File
@@ -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:
@@ -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):
@@ -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:
@@ -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
+1 -1
View File
@@ -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
+2 -2
View File
@@ -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
+2 -2
View File
@@ -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))
+2 -2
View File
@@ -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)
+1 -1
View File
@@ -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)
+1 -1
View File
@@ -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
+2 -2
View File
@@ -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
+1 -1
View File
@@ -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__)
+10 -2
View File
@@ -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
+2 -2
View File
@@ -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