diff --git a/django/applications/catmaid/apps.py b/django/applications/catmaid/apps.py index 7ebbc787b2..8167b3d3a5 100644 --- a/django/applications/catmaid/apps.py +++ b/django/applications/catmaid/apps.py @@ -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() @@ -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: @@ -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() diff --git a/django/applications/catmaid/consumers.py b/django/applications/catmaid/consumers.py index 025b721bb8..bc0b625a61 100644 --- a/django/applications/catmaid/consumers.py +++ b/django/applications/catmaid/consumers.py @@ -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"] @@ -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) @@ -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) diff --git a/django/applications/catmaid/control/authentication.py b/django/applications/catmaid/control/authentication.py index 74c0b8b2fd..5be6d8f4ba 100644 --- a/django/applications/catmaid/control/authentication.py +++ b/django/applications/catmaid/control/authentication.py @@ -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 diff --git a/django/applications/catmaid/control/client.py b/django/applications/catmaid/control/client.py index 988ad91f38..267471247d 100644 --- a/django/applications/catmaid/control/client.py +++ b/django/applications/catmaid/control/client.py @@ -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)}') @@ -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') diff --git a/django/applications/catmaid/control/nat/r.py b/django/applications/catmaid/control/nat/r.py index 16a24ba773..cae9d93663 100644 --- a/django/applications/catmaid/control/nat/r.py +++ b/django/applications/catmaid/control/nat/r.py @@ -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 @@ -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}') @@ -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( @@ -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)) @@ -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( @@ -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)) @@ -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 diff --git a/django/applications/catmaid/control/node.py b/django/applications/catmaid/control/node.py index fe2d7c9641..27edda2a65 100644 --- a/django/applications/catmaid/control/node.py +++ b/django/applications/catmaid/control/node.py @@ -1432,7 +1432,7 @@ 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 @@ -1440,7 +1440,7 @@ def get_node_provider_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 = {} diff --git a/django/applications/catmaid/control/similarity.py b/django/applications/catmaid/control/similarity.py index df45286df8..8b23e16e2f 100644 --- a/django/applications/catmaid/control/similarity.py +++ b/django/applications/catmaid/control/similarity.py @@ -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. diff --git a/django/applications/catmaid/control/skeletonexport.py b/django/applications/catmaid/control/skeletonexport.py index d6a99b6dcb..76ad4c2cbc 100644 --- a/django/applications/catmaid/control/skeletonexport.py +++ b/django/applications/catmaid/control/skeletonexport.py @@ -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: diff --git a/django/applications/catmaid/control/textlabel.py b/django/applications/catmaid/control/textlabel.py index db9639616a..2831b7c923 100644 --- a/django/applications/catmaid/control/textlabel.py +++ b/django/applications/catmaid/control/textlabel.py @@ -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: diff --git a/django/applications/catmaid/management/commands/catmaid_export_data.py b/django/applications/catmaid/management/commands/catmaid_export_data.py index 427ae2cd5c..b67d5118d6 100644 --- a/django/applications/catmaid/management/commands/catmaid_export_data.py +++ b/django/applications/catmaid/management/commands/catmaid_export_data.py @@ -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) @@ -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) diff --git a/django/applications/catmaid/management/commands/catmaid_import_from_trakem2.py b/django/applications/catmaid/management/commands/catmaid_import_from_trakem2.py index 12d3bf074a..15a8b6b7a0 100644 --- a/django/applications/catmaid/management/commands/catmaid_import_from_trakem2.py +++ b/django/applications/catmaid/management/commands/catmaid_import_from_trakem2.py @@ -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, ' diff --git a/django/applications/catmaid/state.py b/django/applications/catmaid/state.py index bde39c3f29..443ea7cbf0 100644 --- a/django/applications/catmaid/state.py +++ b/django/applications/catmaid/state.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import decimal from functools import reduce import json @@ -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) @@ -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. diff --git a/django/applications/catmaid/templatetags/data_view_config.py b/django/applications/catmaid/templatetags/data_view_config.py index 572d96336c..fbbf1e8189 100644 --- a/django/applications/catmaid/templatetags/data_view_config.py +++ b/django/applications/catmaid/templatetags/data_view_config.py @@ -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: diff --git a/django/applications/catmaid/tests/apis/test_skeletons.py b/django/applications/catmaid/tests/apis/test_skeletons.py index 996e9e82af..0d66ad23a0 100644 --- a/django/applications/catmaid/tests/apis/test_skeletons.py +++ b/django/applications/catmaid/tests/apis/test_skeletons.py @@ -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(): diff --git a/django/applications/catmaid/tests/common.py b/django/applications/catmaid/tests/common.py index 26f3f69c89..6a4d05400e 100644 --- a/django/applications/catmaid/tests/common.py +++ b/django/applications/catmaid/tests/common.py @@ -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)) diff --git a/django/applications/catmaid/tests/test_import_export.py b/django/applications/catmaid/tests/test_import_export.py index 549a95ce4e..d5300faac4 100644 --- a/django/applications/catmaid/tests/test_import_export.py +++ b/django/applications/catmaid/tests/test_import_export.py @@ -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) @@ -350,7 +350,7 @@ 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) @@ -358,7 +358,7 @@ def test_result(result): 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 diff --git a/django/lib/custom_swagger_schema.py b/django/lib/custom_swagger_schema.py index d705bd37f2..9f9832f2d4 100644 --- a/django/lib/custom_swagger_schema.py +++ b/django/lib/custom_swagger_schema.py @@ -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)