Skip to content

Commit

Permalink
CI: fix flake warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
tomka committed Dec 5, 2024
1 parent 77ecd2b commit 3a32fa5
Show file tree
Hide file tree
Showing 17 changed files with 45 additions and 47 deletions.
6 changes: 3 additions & 3 deletions django/applications/catmaid/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def check_old_version(sender, **kwargs) -> None:
"""Make sure this migration system starts with all South migrations applied,
in case there are already existing tables."""
# Only validate after catmaid was migrated
if type(sender) != CATMAIDConfig:
if not isinstance(sender, CATMAIDConfig):
return

cursor = connection.cursor()
Expand Down Expand Up @@ -174,7 +174,7 @@ def check_client_settings(app_configs, **kwargs):
logger.info("Force setting instance client settings")

try:
if type(instance_settings) == str:
if isinstance(instance_settings, str):
instance_settings = json.loads(instance_settings)
client.set_instance_settings(instance_settings, force_client_settings)
except json.JSONDecodeError:
Expand All @@ -189,7 +189,7 @@ def check_client_settings(app_configs, **kwargs):
def validate_environment(sender, **kwargs) -> None:
"""Make sure CATMAID is set up correctly."""
# Only validate after catmaid was migrated
if type(sender) != CATMAIDConfig:
if not isinstance(sender, CATMAIDConfig):
return

sender.validate_projects()
Expand Down
6 changes: 3 additions & 3 deletions django/applications/catmaid/consumers.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def connect(self):
"""
# Don't do anything, if there is no channels layer.
if not self.channel_layer:
logger.error(f'UpdateConsumer: can\'t handle WebSockets connection, no channels layer')
logger.error("UpdateConsumer: can't handle WebSockets connection, no channels layer")
return
# Add user to the matching user group
user = self.scope["user"]
Expand All @@ -34,7 +34,7 @@ def disconnect(self, message):
"""
# Don't do anything, if there is no channels layer.
if not self.channel_layer:
logger.error(f'UpdateConsumer: can\'t handle WebSockets disconnect, no channels layer')
logger.error("UpdateConsumer: can't handle WebSockets disconnect, no channels layer")
return
user = self.scope["user"]
async_to_sync(self.channel_layer.group_discard)(get_user_group_name(user.id), self.channel_name)
Expand All @@ -44,7 +44,7 @@ def receive(self, *, text_data):
"""
# Don't do anything, if there is no channels layer.
if not self.channel_layer:
logger.error(f'UpdateConsumer: can\'t handle WebSockets message, no channels layer')
logger.error("UpdateConsumer: can't handle WebSockets message, no channels layer")
return
user = self.scope["user"]
text_data_json = json.loads(text_data)
Expand Down
2 changes: 1 addition & 1 deletion django/applications/catmaid/control/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -894,7 +894,7 @@ def activate(request:HttpRequest, uidb64, token):
try:
uid = force_str(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, User.DoesNotExist):
except (TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
if user is not None and account_activation_token.check_token(user, token):
user.is_active = True
Expand Down
4 changes: 2 additions & 2 deletions django/applications/catmaid/control/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ def put(self, request:Request, name:Optional[int]=None, format=None) -> Response

# We expect also an actual object, not a single string or number, which
# is represented as a dict in Python.
if type(value) != dict:
if not isinstance(value, dict):
raise ValidationError(f'Data is of type "{type(value)}", but '
f'expected an object: {str(value)}')

Expand Down Expand Up @@ -336,7 +336,7 @@ def set_instance_settings(settings, force=False):
settings familiy, e.g. "neuron-name-service" and the value is the respective
settings data.
"""
if type(settings) != dict:
if not isinstance(settings, dict):
raise ValueError("Settings needs to be a dictionry")

data_store = ClientDatastore.objects.get(name='settings')
Expand Down
14 changes: 7 additions & 7 deletions django/applications/catmaid/control/nat/r.py
Original file line number Diff line number Diff line change
Expand Up @@ -661,7 +661,7 @@ def create_dps_data_cache(project_id, object_type, tangent_neighbors=20,
'.parallel': parallel,
})
# Make sure unneeded R objects are deleted
del(objects)
del objects
gc.collect()
objects = simplified_objects

Expand All @@ -674,7 +674,7 @@ def create_dps_data_cache(project_id, object_type, tangent_neighbors=20,
'OmitFailures': omit_failures,
})

del(objects)
del objects

# Save cache to disk
logger.debug(f'Storing skeleton cache with {len(objects_dps)} entries: {cache_path}')
Expand Down Expand Up @@ -836,7 +836,7 @@ def nblast(project_id, user_id, config_id, query_object_ids, target_object_ids,
# TODO: There must be a simler way to extract non-NA values only
query_object_id_str = rinterface.StrSexpVector(list(map(str, query_object_ids)))
query_cache_objects_dps = skeleton_cache.rx(query_object_id_str)
non_na_ids = list(filter(lambda x: type(x) == str,
non_na_ids = list(filter(lambda x: isinstance(x, str),
list(base.names(query_cache_objects_dps))))
cache_typed_query_object_ids = non_na_ids
query_cache_objects_dps = rnat.subset_neuronlist(
Expand Down Expand Up @@ -897,7 +897,7 @@ def nblast(project_id, user_id, config_id, query_object_ids, target_object_ids,
# TODO: There must be a simler way to extract non-NA values only
query_object_id_str = rinterface.StrSexpVector(list(map(str, query_object_ids)))
query_cache_objects_dps = pointcloud_cache.rx(query_object_id_str) # type: ignore # not provable that cache will be initialised
non_na_ids = list(filter(lambda x: type(x) == str,
non_na_ids = list(filter(lambda x: isinstance(x, str),
list(base.names(query_cache_objects_dps))))
query_cache_objects_dps = rnat.subset_neuronlist(
query_cache_objects_dps, rinterface.StrSexpVector(non_na_ids))
Expand Down Expand Up @@ -1000,7 +1000,7 @@ def nblast(project_id, user_id, config_id, query_object_ids, target_object_ids,
# TODO: There must be a simler way to extract non-NA values only
target_object_id_str = rinterface.StrSexpVector(list(map(str, target_object_ids)))
target_cache_objects_dps = skeleton_cache.rx(target_object_id_str)
non_na_ids = list(filter(lambda x: type(x) == str,
non_na_ids = list(filter(lambda x: isinstance(x, str),
list(base.names(target_cache_objects_dps))))
cache_typed_target_object_ids = non_na_ids
target_cache_objects_dps = rnat.subset_neuronlist(
Expand Down Expand Up @@ -1062,7 +1062,7 @@ def nblast(project_id, user_id, config_id, query_object_ids, target_object_ids,
# TODO: There must be a simler way to extract non-NA values only
target_object_id_str = rinterface.StrSexpVector(list(map(str, target_object_ids)))
target_cache_objects_dps = pointcloud_cache.rx(target_object_id_str) # type: ignore
non_na_ids = list(filter(lambda x: type(x) == str,
non_na_ids = list(filter(lambda x: isinstance(x, str),
list(base.names(target_cache_objects_dps))))
target_cache_objects_dps = rnat.subset_neuronlist(
target_cache_objects_dps, rinterface.StrSexpVector(non_na_ids))
Expand Down Expand Up @@ -1633,7 +1633,7 @@ def neuronlist_for_skeletons(project_id, skeleton_ids, omit_failures=False,
})
print(f"Converted {len(objects)}/{len(skeleton_ids)} neurons")

del(cs_r)
del cs_r
gc.collect()

return objects
4 changes: 2 additions & 2 deletions django/applications/catmaid/control/node.py
Original file line number Diff line number Diff line change
Expand Up @@ -1432,15 +1432,15 @@ def get_tuples(self, params, project_id, explicit_treenode_ids,
def get_node_provider_configs():
"""Get a list of specified node provider configurationss."""
configs = settings.NODE_PROVIDERS
if type(configs) == str:
if isinstance(configs, str):
configs = [configs]
return configs


def get_configured_node_providers(provider_entries, connection=None,
enabled_only=False) -> List:
node_providers = []
if type(provider_entries) == str:
if isinstance(provider_entries, str):
provider_entries = [provider_entries]
for entry in provider_entries:
options:Dict = {}
Expand Down
8 changes: 4 additions & 4 deletions django/applications/catmaid/control/similarity.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,16 +338,16 @@ def put(self, request:Request, project_id) -> Response:
if matching_subset:
matching_subset = json.loads(matching_subset)

if type(matching_subset) != list:
if not isinstance(matching_subset, list):
raise ValueError("Expected matching_subset to be a list")

for subset in matching_subset:
if type(subset) != list:
if not isinstance(subset, list):
raise ValueError("Expected all matching_subset elements to be list")
for element in subset:
if type(element) != list or len(element) != 2:
if not isinstance(element, list) or len(element) != 2:
raise ValueError("Expeceted subset elements to be lists with two elements")
if type(element[0]) not in (int, list) or type(element[1]) != int:
if type(element[0]) not in (int, list) or not isinstance(element[1], int):
raise ValueError("Expected subset selements to consist of ints or lists of ints")

# Load and store point sets, if there are any.
Expand Down
2 changes: 1 addition & 1 deletion django/applications/catmaid/control/skeletonexport.py
Original file line number Diff line number Diff line change
Expand Up @@ -668,7 +668,7 @@ def _compact_skeleton(project_id, skeleton_id, with_connectors=True,
SELECT relation_name, id FROM relation WHERE project_id=%(project_id)s
""", {
'project_id': project_id,
})
})
relations = dict(cursor.fetchall())

if with_connectors:
Expand Down
14 changes: 7 additions & 7 deletions django/applications/catmaid/control/textlabel.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,14 +175,14 @@ def textlabels(request:HttpRequest, project_id=None) -> JsonResponse:
response_on_error = 'Failed to format output'
for tl in textlabels:
tl['colour'] = {'r': tl['r'], 'g': tl['g'], 'b': tl['b'], 'a': tl['a']}
del(tl['r'])
del(tl['g'])
del(tl['b'])
del(tl['a'])
del tl['r']
del tl['g']
del tl['b']
del tl['a']
tl['location'] = {'x': tl['x'], 'y': tl['y'], 'z': tl['z']}
del(tl['x'])
del(tl['y'])
del(tl['z'])
del tl['x']
del tl['y']
del tl['z']
if tl['scaling']:
tl['scaling'] = 1
else:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -989,7 +989,7 @@ def collect_data(self):
seen_deep_links = set()
if self.export_public_deep_links:
deep_links = DeepLink.objects.filter(project_id=self.project.id, is_public=True)
seen_deep_links.update([l.id for l in deep_links])
seen_deep_links.update([link.id for link in deep_links])
logger.info(f'Exporting {len(deep_links)} public deep links')
self.to_serialize.append(deep_links)

Expand All @@ -998,7 +998,7 @@ def collect_data(self):
deep_links = DeepLink.objects.filter(project_id=self.project.id, is_exportable=True)
n_exportable_deep_links = len(deep_links)
deep_links = list(filter(lambda x: x.id not in seen_deep_links, deep_links))
seen_deep_links.update([l.id for l in deep_links])
seen_deep_links.update([link.id for link in deep_links])
logger.info(f'Exporting {n_exportable_deep_links} exportable deep links ({len(deep_links)} are not already prev. included)')
self.to_serialize.append(deep_links)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ def __init__(self, t, r, transformer, side:SynapseSides, parent_neuron_id:int,
if type(d) in (TrakEM2.AreaTree, TrakEM2.AreaList)]

if len(self.displayables) > 1:
arealists = list(filter(lambda x: type(x) == TrakEM2.AreaList, self.displayables))
arealists = list(filter(lambda x: isinstance(x, TrakEM2.AreaList), self.displayables))
n_arealists = len(arealists)
if n_arealists == 1:
log('Can only assign connector node to a single displayable, '
Expand Down
6 changes: 2 additions & 4 deletions django/applications/catmaid/state.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

import decimal
from functools import reduce
import json
Expand Down Expand Up @@ -216,7 +214,7 @@ def collect_state_checks(node_id, state, cursor, node=False,
if not all(has_only_truthy_values(e) for e in child_nodes):
raise ValueError("No valid state provided, invalid children")

if type(children) == bool:
if isinstance(children, bool):
state_checks.append(make_all_children_query(
[int(c[0]) for c in child_nodes], node_id))
state_checks.extend(StateCheck(SQL.was_edited, (c[0], c[1], c[1])) for c in child_nodes)
Expand Down Expand Up @@ -331,7 +329,7 @@ def lock_nodes(node_ids, cursor) -> None:
raise ValueError("No nodes to lock")

def is_disabled(state) -> bool:
return state and type(state) == dict and state.get('nocheck') is True
return state and isinstance(state, dict) and state.get('nocheck') is True

def make_nocheck_state(parsed=False):
"""Get a state representation that causes skipping of actual state checks.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def render(self, context):
tag = t.resolve(context)
if not tag:
continue
elif type(tag) == list:
elif isinstance(tag, list):
for subtag in tag:
current_tags.append(subtag)
else:
Expand Down
4 changes: 2 additions & 2 deletions django/applications/catmaid/tests/apis/test_skeletons.py
Original file line number Diff line number Diff line change
Expand Up @@ -980,8 +980,8 @@ def test_export_skeleton_reviews(self):

skeleton_id = 235

def first_element(l):
return l[0]
def first_element(node_entry):
return node_entry[0]

def sort_json_nodes(node_result):
for k,v in expected_result.items():
Expand Down
4 changes: 2 additions & 2 deletions django/applications/catmaid/tests/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,12 +110,12 @@ def fake_authentication(self):
self.client.login(username='temporary', password='temporary')


def round_list(l, digits=6):
def round_list(value_list, digits=6):
"""Round floating point values in a list recursively to the specified number
of digits.
"""
new_list = []
for v in l:
for v in value_list:
v_type = type(v)
if v_type == float:
new_list.append(round(v, digits))
Expand Down
8 changes: 4 additions & 4 deletions django/applications/catmaid/tests/test_import_export.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,12 +331,12 @@ def test_import_export_projects(self):
def strip_ids(d):
""" Recursively, strip all 'id' fields of dictionaries.
"""
if type(d) == dict:
if isinstance(d, dict):
if 'id' in d:
d.pop('id')
for _,v in d.items():
strip_ids(v)
if type(d) == list:
if isinstance(d, list):
for v in d:
strip_ids(v)

Expand All @@ -350,15 +350,15 @@ def test_result(result):
# results in tuples).
if 'project' in p:
if 'stacks' in p['project']:
if type(p['project']['stacks']) == tuple:
if isinstance(p['project']['stacks'], tuple):
p['project']['stacks'] = list(p['project']['stacks'])
self.assertDictEqual(cp, p)

self.fake_authentication()

def parse_list(d):
for k in d:
if type(d[k]) == tuple:
if isinstance(d[k], tuple):
d[k] = list(d[k])
return d

Expand Down
2 changes: 1 addition & 1 deletion django/lib/custom_swagger_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def get_link(self, path, method, base_url):
# a block quote (due to Python comments being indented).
_method_desc = '\n'.join(line.strip() for line in _method_desc.splitlines())

if yaml_doc and type(yaml_doc) != str:
if yaml_doc and not isinstance(yaml_doc, str):
params = yaml_doc.get('parameters', [])

params_type = type(params)
Expand Down

0 comments on commit 3a32fa5

Please sign in to comment.