misc: pylint fix unidiomatic-typecheck (#52222)

This commit is contained in:
Lauréline Guérin 2021-03-22 09:23:31 +01:00
parent f21431cb8a
commit 9b448b3232
No known key found for this signature in database
GPG Key ID: 1FAB9B9B4F93D473
17 changed files with 50 additions and 51 deletions

View File

@ -178,7 +178,7 @@ class UserFieldsDirectory(FieldsDirectory):
form = Form(action='mapping', id='mapping')
field_name_value = users_cfg.get('field_name')
if type(field_name_value) is str:
if isinstance(field_name_value, str):
field_name_value = [field_name_value]
form.add(
WidgetList,

View File

@ -190,7 +190,7 @@ class CustomView(StorableObject):
for k, v in sorted(field_dict.items()):
text_value = force_text(v, charset, errors='replace')
ET.SubElement(el, k).text = text_value
elif type(val) is dict:
elif isinstance(val, dict):
for k, v in sorted(val.items()):
text_value = force_text(v, charset, errors='replace')
ET.SubElement(el, k).text = text_value

View File

@ -335,10 +335,10 @@ class Field:
continue
if hasattr(self, attribute) and getattr(self, attribute) is not None:
val = getattr(self, attribute)
if type(val) is dict and not val:
if isinstance(val, dict) and not val:
continue
el = ET.SubElement(field, attribute)
if type(val) is dict:
if isinstance(val, dict):
for k, v in sorted(val.items()):
if isinstance(v, str):
text_value = force_text(v, charset, errors='replace')
@ -347,7 +347,7 @@ class Field:
# import_to_xml to handle import
text_value = force_text(v)
ET.SubElement(el, k).text = text_value
elif type(val) is list:
elif isinstance(val, list):
if attribute[-1] == 's':
atname = attribute[:-1]
else:
@ -371,9 +371,9 @@ class Field:
if el is None:
continue
if list(el):
if type(getattr(self, attribute)) is list:
if isinstance(getattr(self, attribute), list):
v = [xml_node_text(x) for x in el]
elif type(getattr(self, attribute)) is dict:
elif isinstance(getattr(self, attribute), dict):
v = {}
for e in el:
v[e.tag] = xml_node_text(e)
@ -391,7 +391,7 @@ class Field:
setattr(self, attribute, None)
elif el.text in ('False', 'True'): # bools
setattr(self, attribute, el.text == 'True')
elif type(getattr(self, attribute)) is int:
elif isinstance(getattr(self, attribute), int):
setattr(self, attribute, int(el.text))
else:
setattr(self, attribute, xml_node_text(el))
@ -1616,7 +1616,7 @@ class DateField(WidgetField):
return ''
def add_to_form(self, form, value=None):
if value and type(value) is not str:
if value and not isinstance(value, str):
value = self.convert_value_to_str(value)
return WidgetField.add_to_form(self, form, value=value)
@ -1897,7 +1897,7 @@ class ItemField(WidgetField, MapOptionsMixin, ItemFieldMixin):
kwargs['options'] = [(None, '---', None)]
if display_mode == 'radio':
self.widget_class = RadiobuttonsWidget
if type(kwargs['options'][0]) is str:
if isinstance(kwargs['options'][0], str):
first_items = [x for x in kwargs['options'][:3]]
else:
first_items = [x[1] for x in kwargs['options'][:3]]
@ -2293,7 +2293,7 @@ class ItemsField(WidgetField, ItemFieldMixin):
r += htmltext('</ul>')
return r.getvalue()
if type(value) is str: # == display_value
if isinstance(value, str): # == display_value
return value
if value:
try:
@ -2343,7 +2343,7 @@ class ItemsField(WidgetField, ItemFieldMixin):
return ''
choices = []
for choice in data.get(field_id) or []:
if type(options[0]) is str:
if isinstance(options[0], str):
choices.append(choice)
elif type(options[0]) in (tuple, list):
if len(options[0]) == 2:
@ -3120,7 +3120,7 @@ class RankedItemsField(WidgetField):
def get_csv_value(self, value, **kwargs):
if not self.items:
return ['']
if type(value) is not dict:
if not isinstance(value, dict):
value = {}
items = [x for x in value.items() if x[1] is not None]
items.sort(key=lambda x: x[1])

View File

@ -86,12 +86,12 @@ def get_dict_with_varnames(fields, data, formdata=None, varnames_only=False):
new_data['var_%s_raw' % field.varname] = raw_value
if data is not None:
structured_value = field.get_structured_value(data)
if type(structured_value) is dict:
if isinstance(structured_value, dict):
for k, v in structured_value.items():
if k in ('id', 'text'):
continue
new_data['var_%s_%s' % (field.varname, k)] = v
if type(structured_value) is list:
if isinstance(structured_value, list):
for i, struct_value in enumerate(structured_value):
for k, v in struct_value.items():
if k in ('id', 'text'):
@ -105,7 +105,7 @@ def get_dict_with_varnames(fields, data, formdata=None, varnames_only=False):
def flatten_dict(d):
for k, v in list(d.items()):
if type(v) is dict:
if isinstance(v, dict):
flatten_dict(v)
for k2, v2 in v.items():
d['%s_%s' % (k, k2)] = v2

View File

@ -207,7 +207,7 @@ class FormDef(StorableObject):
self.url_name = self.get_new_url_name()
changed = True
if self.fields and type(self.fields[0]) is dict:
if self.fields and isinstance(self.fields[0], dict):
for f in self.fields:
if 'name' in f:
f['label'] = f['name']
@ -251,17 +251,17 @@ class FormDef(StorableObject):
self.max_field_id = max([lax_int(x.id) for x in self.fields])
changed = True
if type(self.category_id) is int:
if isinstance(self.category_id, int):
self.category_id = str(self.category_id)
changed = True
if type(self.workflow_id) is int:
if isinstance(self.workflow_id, int):
self.workflow_id = str(self.workflow_id)
changed = True
if self.roles:
for role in self.roles:
if type(role) is int:
if isinstance(role, int):
self.roles = [str(x) for x in self.roles]
changed = True
break
@ -269,7 +269,7 @@ class FormDef(StorableObject):
if self.workflow_roles:
workflow_roles_list = self.workflow_roles.items()
for role_id in self.workflow_roles.values():
if type(role_id) is int:
if isinstance(role_id, int):
self.workflow_roles = dict([(x, str(y)) for x, y in workflow_roles_list])
changed = True
break
@ -651,7 +651,7 @@ class FormDef(StorableObject):
if not field.has_live_conditions(self):
# no live conditions so field can be skipped
continue
if type(displayed_fields) is list:
if isinstance(displayed_fields, list):
displayed_fields.append(field)
value = None
if form_data:
@ -827,7 +827,7 @@ class FormDef(StorableObject):
if not hasattr(self, attribute):
continue
root[attribute] = getattr(self, attribute)
if type(root[attribute]) is time.struct_time:
if isinstance(root[attribute], time.struct_time):
root[attribute] = time.strftime('%Y-%m-%dT%H:%M:%S', root[attribute])
root['fields'] = []

View File

@ -139,8 +139,7 @@ class Ctl:
self.load_all_commands()
print()
commands = [(x.name, x.doc) for x in self.get_commands().values()]
commands.sort()
commands = sorted([(x.name, x.doc) for x in self.get_commands().values()])
print('Available commands:')
for name, description in commands:
print(' %-15s %s' % (name, description))

View File

@ -298,7 +298,7 @@ def email(
if hide_recipients or email_rcpt is None:
msg['To'] = 'Undisclosed recipients:;'
else:
if type(email_rcpt) is list:
if isinstance(email_rcpt, list):
msg['To'] = ', '.join(email_rcpt)
else:
msg['To'] = email_rcpt
@ -326,7 +326,7 @@ def email(
for key, value in extra_headers.items():
msg[key] = value
if type(email_rcpt) is list:
if isinstance(email_rcpt, list):
rcpts = email_rcpt[:]
else:
rcpts = [email_rcpt]

View File

@ -700,7 +700,7 @@ def _write_value(valrefs, fp, ctx, format=lambda s: s):
# if the value has a 'read' attribute, then it is a stream: copy it
if hasattr(value, 'read'):
while 1:
while True:
chunk = value.read(16384)
if not chunk:
break

View File

@ -2249,10 +2249,10 @@ class RankedItemsWidget(CompositeWidget):
del kwargs['randomize_items']
for v in elements:
if type(v) is tuple:
if isinstance(v, tuple):
title = v[1]
key = v[0]
if type(key) is int:
if isinstance(key, int):
name = 'element%d' % v[0]
elif type(key) in (str, htmltext):
name = str('element%s' % v[0])
@ -2290,7 +2290,7 @@ class RankedItemsWidget(CompositeWidget):
value = self.get(name)
if value is not None:
values[self.element_names[name]] = value
if value is not None and type(value) is not int:
if value is not None and not isinstance(value, int):
self.get_widget(name).set_error(IntWidget.TYPE_ERROR)
self.value = values or None

View File

@ -70,7 +70,7 @@ def humanduration2seconds(humanduration):
def seconds2humanduration(seconds):
"""Convert a time range in seconds to a human string representation"""
if not type(seconds) is int:
if not isinstance(seconds, int):
return ""
days = int(seconds / _day)

View File

@ -246,7 +246,7 @@ class AdminIDPDir(Directory):
r += htmltext('<ul class="biglist">')
for kidp, idp in sorted(get_cfg('idp', {}).items(), key=lambda k: k[0]):
p = None
if idp and type(idp) is dict:
if idp and isinstance(idp, dict):
p = lasso.Provider(
lasso.PROVIDER_ROLE_IDP,
misc.get_abs_path(idp.get('metadata')),

View File

@ -82,7 +82,7 @@ class Formatter(logging.Formatter):
user_id = user
else:
user_id = user.id
if type(user_id) is str and user_id.startswith('anonymous-'):
if isinstance(user_id, str) and user_id.startswith('anonymous-'):
# legacy; kept for ancient log entries
user_id = 'anonymous'
else:

View File

@ -599,7 +599,7 @@ class StorableObject:
if not hasattr(object, index) or getattr(object, index) is None:
continue
attribute = getattr(object, index)
if type(attribute) is dict:
if isinstance(attribute, dict):
attribute = attribute.values()
elif type(attribute) not in (tuple, list, set):
attribute = [attribute]
@ -769,7 +769,7 @@ class StorableObject:
pass
old_value = []
if type(getattr(self, index)) is dict:
if isinstance(getattr(self, index), dict):
new_value = getattr(self, index).values()
if previous_object_value:
old_value = getattr(previous_object_value, index)
@ -787,7 +787,7 @@ class StorableObject:
new_value = [getattr(self, index)]
if previous_object_value:
old_raw_value = getattr(previous_object_value, index)
if type(old_raw_value) is dict:
if isinstance(old_raw_value, dict):
old_value = old_raw_value.values()
elif type(old_raw_value) in (tuple, list, set):
old_value = old_raw_value

View File

@ -356,7 +356,7 @@ def get_decorate_vars(body, response, generate_breadcrumb=True, **kwargs):
s.append('<a href="%s">%s</a>' % (component, label))
continue
if label is not None:
if type(label) is str:
if isinstance(label, str):
label = htmlescape(label)
if not is_in_backoffice and (
total_len > 80 and len(label) > 10 and response.breadcrumb[-1] != (component, label)

View File

@ -1682,7 +1682,7 @@ class SqlMixin:
elif sql_type == 'varchar':
assert isinstance(value, str)
elif sql_type == 'date':
assert type(value) is time.struct_time
assert isinstance(value, time.struct_time)
value = datetime.datetime(value.tm_year, value.tm_mon, value.tm_mday)
elif sql_type == 'bytea':
value = bytearray(pickle.dumps(value, protocol=2))
@ -2202,7 +2202,7 @@ class SqlDataMixin(SqlMixin):
where_clauses, parameters, func_clause = parse_clause(clause)
assert not func_clause
if type(value) is int:
if isinstance(value, int):
value = str(value)
if '%s_array' % index in [x[0] for x in cls._table_static_fields]:

View File

@ -64,7 +64,7 @@ class User(StorableObject):
if self.roles:
for role in self.roles:
if type(role) is int:
if isinstance(role, int):
self.roles = [str(x) for x in self.roles]
changed = True
break
@ -124,7 +124,7 @@ class User(StorableObject):
self.email = formdata.get(field_email)
field_name_values = users_cfg.get('field_name')
if type(field_name_values) is str: # it was a string in previous versions
if isinstance(field_name_values, str): # it was a string in previous versions
field_name_values = [field_name_values]
if field_name_values:

View File

@ -957,10 +957,10 @@ class XmlSerialisable:
if hasattr(self, attribute) and getattr(self, attribute) is not None:
el = ET.SubElement(node, attribute)
val = getattr(self, attribute)
if type(val) is dict:
if isinstance(val, dict):
for k, v in val.items():
ET.SubElement(el, k).text = force_text(v, charset, errors='replace')
elif type(val) is list:
elif isinstance(val, list):
if attribute[-1] == 's':
atname = attribute[:-1]
else:
@ -986,9 +986,9 @@ class XmlSerialisable:
if el is None:
continue
if list(el):
if type(getattr(self, attribute)) is list:
if isinstance(getattr(self, attribute), list):
v = [xml_node_text(x) or '' for x in el]
elif type(getattr(self, attribute)) is dict:
elif isinstance(getattr(self, attribute), dict):
v = {}
for e in el:
v[e.tag] = xml_node_text(e)
@ -1002,7 +1002,7 @@ class XmlSerialisable:
elif el.text in ('False', 'True') and not isinstance(getattr(self, attribute), str):
# booleans
setattr(self, attribute, el.text == 'True')
elif type(getattr(self, attribute)) is int:
elif isinstance(getattr(self, attribute), int):
setattr(self, attribute, int(el.text))
else:
setattr(self, attribute, xml_node_text(el))
@ -1592,7 +1592,7 @@ class WorkflowStatus:
if other is None:
return False
# this assumes both status are from the same workflow
if type(other) is str:
if isinstance(other, str):
other_id = other
else:
other_id = other.id
@ -1900,7 +1900,7 @@ class WorkflowStatusItem(XmlSerialisable):
changed = False
for roles_attribute in ('to', 'by'):
attribute_value = getattr(self, roles_attribute, []) or []
if any((x for x in attribute_value if type(x) is int)):
if any((x for x in attribute_value if isinstance(x, int))):
setattr(self, roles_attribute, [str(x) for x in attribute_value])
changed = True
return changed
@ -2043,7 +2043,7 @@ class WorkflowStatusItem(XmlSerialisable):
if hasattr(self, 'get_%s_parameter_view_value' % parameter):
return getattr(self, 'get_%s_parameter_view_value' % parameter)()
value = getattr(self, parameter)
if type(value) is bool:
if isinstance(value, bool):
return _('Yes') if value else _('No')
elif hasattr(widget, 'options') and value:
for option in widget.options:
@ -2510,7 +2510,7 @@ class CommentableWorkflowStatusItem(WorkflowStatusItem):
setattr(self, f, widget.parse())
def fill_admin_form(self, form):
if self.by and not type(self.by) is list:
if self.by and not isinstance(self.by, list):
self.by = None
return super().fill_admin_form(form)