Fix various flake8 errors

This commit is contained in:
Procyonae
2025-01-13 12:27:05 +00:00
parent 40a53b3a03
commit 07b941ed35
16 changed files with 58 additions and 57 deletions
+2 -2
View File
@@ -56,7 +56,7 @@ total_conversions = set()
for info in glob.glob('data/mods/*/modinfo.json'):
mod_info = json.load(open(info, encoding='utf-8'))
for e in mod_info:
if(e["type"] == "MOD_INFO" and
if (e["type"] == "MOD_INFO" and
("obsolete" not in e or not e["obsolete"])):
ident = e["id"]
all_mod_dependencies[ident] = e.get("dependencies", [])
@@ -72,7 +72,7 @@ for r, d, f in os.walk('data/mods'):
info_path = os.path.join(r, 'modinfo.json')
mod_info = json.load(open(info_path, encoding='utf-8'))
for e in mod_info:
if(e["type"] == "MOD_INFO" and
if (e["type"] == "MOD_INFO" and
("obsolete" not in e or not e["obsolete"])):
ident = e["id"]
if ident == "":
+1 -1
View File
@@ -19,7 +19,7 @@ def strip_pot_file(filename):
except IOError as read_exc:
print(read_exc)
sys.exit(1)
assert(len(to_write) > 1) # Wrong .pot file
assert len(to_write) > 1 # Wrong .pot file
to_write = strip_line_numbers(to_write)
to_write = strip_repeated_comments(to_write)
+6 -6
View File
@@ -18,9 +18,9 @@ TAGS_FILE = os.path.join(TOP_DIR, "tags")
def cdda_style_json(v):
if type(v) == str:
if type(v) is str:
return json.dumps(v)
elif type(v) == list:
elif type(v) is list:
return f'[ {", ".join(cdda_style_json(e) for e in v)} ]'
else:
raise RuntimeError('Unexpected type')
@@ -53,9 +53,9 @@ def main(args):
def add_definition(id_key, id, full_id, relative_path):
if not id:
return
if type(id) == str:
if type(id) is str:
definitions.append((id_key, id, full_id, relative_path))
elif type(id) == list:
elif type(id) is list:
for i in id:
add_definition(id_key, i, full_id, relative_path)
@@ -73,9 +73,9 @@ def main(args):
"Problem reading file %s, reason: %s" %
(filename, err))
continue
if type(json_data) == dict:
if type(json_data) is dict:
json_data = [json_data]
elif type(json_data) != list:
elif type(json_data) is not list:
sys.stderr.write(
"Problem parsing data from file %s, reason: "
"expected a list." % filename)
+2 -2
View File
@@ -154,7 +154,7 @@ def get_armor_data(jo):
# This will be done again in the recursive function
# But we do it here for an early return on no data
read_armor_data(jo, dat)
if("armor" not in jo and
if ("armor" not in jo and
(len(dat) == 0 or (len(dat) == 1 and "material" in dat))):
return dict()
@@ -274,7 +274,7 @@ def gen_new(path):
for key in transferred_keys:
if key != "material" and key in jo:
del(jo[key])
del jo[key]
return json_data if change else None
+1 -1
View File
@@ -53,7 +53,7 @@ def gen_new(path):
if key not in jo:
continue
jo["extend"][key] = jo[key]
del(jo[key])
del jo[key]
return json_data if change else None
+1 -2
View File
@@ -14,8 +14,7 @@ Example usages:
import sys
import json
import argparse
from util import import_data, key_counter, ui_counts_to_columns,\
WhereAction
from util import import_data, key_counter, ui_counts_to_columns, WhereAction
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+1 -1
View File
@@ -50,7 +50,7 @@ if __name__ == "__main__":
sys.exit(1)
# We'll either get a dict or a list...
if type(json_data) == dict:
if type(json_data) is dict:
# ... and just make it a list.
json_data = [json_data]
+5 -5
View File
@@ -14,18 +14,18 @@ def gen_new(path):
with open(path, "r", encoding="utf-8") as json_file:
json_data = json.load(json_file)
for jo in json_data:
if (type(jo) == dict and "type" in jo and
if (type(jo) is dict and "type" in jo and
jo["type"] == "MONSTER_FACTION"):
if "by_mood" in jo and type(jo["by_mood"]) == str:
if "by_mood" in jo and type(jo["by_mood"]) is str:
jo["by_mood"] = [jo.pop("by_mood")]
change = True
if "neutral" in jo and type(jo["neutral"]) == str:
if "neutral" in jo and type(jo["neutral"]) is str:
jo["neutral"] = [jo.pop("neutral")]
change = True
if "friendly" in jo and type(jo["friendly"]) == str:
if "friendly" in jo and type(jo["friendly"]) is str:
jo["friendly"] = [jo.pop("friendly")]
change = True
if "hate" in jo and type(jo["hate"]) == str:
if "hate" in jo and type(jo["hate"]) is str:
jo["hate"] = [jo.pop("hate")]
change = True
+1 -1
View File
@@ -28,7 +28,7 @@ def gen_new(path):
continue
if not jo.get('name'):
continue
if type(jo['name']) == dict:
if type(jo['name']) is dict:
continue
if jo.get('type') not in ['AMMO', 'ARMOR', 'BATTERY', 'bionic',
'BIONIC_ITEM', 'BIONIC_ITEM', 'BOOK',
@@ -71,7 +71,7 @@ def main():
for f in files:
dialogues = []
with open(input_dir + f, encoding="utf-8") as fp:
print(f"Reading from {input_dir+f}")
print(f"Reading from {input_dir + f}")
json_data = json.load(fp)
for obj in json_data:
@@ -82,7 +82,7 @@ def main():
if dialogues:
with open(output_dir + f, "w", encoding="utf-8") as fp:
print(f" Writing to {output_dir+f}")
print(f" Writing to {output_dir + f}")
json.dump(dialogues, fp, ensure_ascii=False, indent=" ")
+16 -16
View File
@@ -39,8 +39,8 @@ def import_data(json_dir=JSON_DIR, json_fmatch=JSON_FNMATCH):
errors.append(
"Problem reading file {},".format(json_file) +
" reason: {}".format(err))
if type(candidates) != list:
if type(candidates) == OrderedDict:
if type(candidates) is not list:
if type(candidates) is OrderedDict:
data.append(candidates)
else:
errors.append(
@@ -56,13 +56,13 @@ def match_primitive_values(item_value, where_value):
"""Perform any odd logic on item matching.
"""
# Matching interpolation for keyboard constrained input.
if type(item_value) == str:
if type(item_value) is str:
# Direct match
return bool(re.match(where_value, item_value))
elif type(item_value) == int or type(item_value) == float:
elif type(item_value) is int or type(item_value) is float:
# match after string conversion
return bool(re.match(where_value, str(item_value)))
elif type(item_value) == bool:
elif type(item_value) is bool:
# help conversion to JSON booleans from the commandline
return bool(re.match(where_value, str(item_value).lower()))
else:
@@ -86,14 +86,14 @@ def matches_where(item, where_key, where_value):
# So we have some value.
item_value = item[where_key]
# Matching interpolation for keyboard constrained input.
if type(item_value) == list:
if type(item_value) is list:
# 1 level deep.
for next_level in item_value:
if match_primitive_values(next_level, where_value):
return True
# else...
return False
elif type(item_value) == dict:
elif type(item_value) is dict:
# Match against the keys of the dictionary... I question my logic.
# 1 level deep.
for next_level in item_value:
@@ -179,14 +179,14 @@ def key_counter(data, where_fn_list):
val = item[key]
# If value is an object, tally key.subkey for all object subkeys
if type(val) == OrderedDict:
if type(val) is OrderedDict:
for subkey in val.keys():
if not subkey.startswith('//'):
stats[key + '.' + subkey] += 1
# If value is a list of objects, tally key.subkey for each
elif type(val) == list:
if all(type(e) == OrderedDict for e in val):
elif type(val) is list:
if all(type(e) is OrderedDict for e in val):
for obj in val:
for subkey in obj.keys():
if not subkey.startswith('//'):
@@ -208,13 +208,13 @@ def item_value_counter(_value):
if isinstance(_value, str):
stats[_value] += 1
# Cast numbers to strings
elif type(_value) == int or type(_value) == float:
elif type(_value) is int or type(_value) is float:
stats[str(_value)] += 1
# Pull all values from objects
elif type(_value) == OrderedDict:
elif type(_value) is OrderedDict:
stats += list_value_counter(list(_value.values()))
# Pull values from list of objects or strings
elif type(_value) == list:
elif type(_value) is list:
stats += list_value_counter(_value)
else:
raise ValueError("Value '%s' has unknown type %s" %
@@ -267,14 +267,14 @@ def value_counter(data, search_key, where_fn_list):
# If this value is a list of objects, pull parent_key.child_key
# values from all of them to include in stats
if type(parent_val) == list and all(type(e) == OrderedDict
if type(parent_val) is list and all(type(e) is OrderedDict
for e in parent_val):
for od in parent_val:
if child_key in od:
stat_vals.append(od[child_key])
# If this value is a single object, get value at parent_key.child_key
elif type(parent_val) == OrderedDict and child_key in parent_val:
elif type(parent_val) is OrderedDict and child_key in parent_val:
stat_vals.append(parent_val[child_key])
# Other kinds of data cannot be indexed by parent_key.child_key
@@ -381,7 +381,7 @@ class CDDAJSONWriter(object):
while items:
k, v = items.pop(0)
# Special cases first.
if (k == "tools" or k == "components") and type(v) == list:
if (k == "tools" or k == "components") and type(v) is list:
self.list_of_lists(k, v)
else:
self.write_primitive_key_val(k, v)
+1 -2
View File
@@ -5,8 +5,7 @@
import argparse
import sys
import json
from util import import_data, value_counter, ui_counts_to_columns,\
WhereAction
from util import import_data, value_counter, ui_counts_to_columns, WhereAction
parser = argparse.ArgumentParser(description="""Count the number of
times a specific values occurs for a specific key. The key may be a
+9 -9
View File
@@ -81,10 +81,10 @@ def info_folder(format: str) -> None:
min_cx, max_cx = cx * 32, cx * 32 + 31
min_cy, max_cy = cy * 32, cy * 32 + 31
o1 = f"{min_cx//180} {min_cy//180}"
o2 = f"{min_cx//180} {max_cy//180}"
o3 = f"{max_cx//180} {min_cy//180}"
o4 = f"{max_cx//180} {max_cy//180}"
o1 = f"{min_cx // 180} {min_cy // 180}"
o2 = f"{min_cx // 180} {max_cy // 180}"
o3 = f"{max_cx // 180} {min_cy // 180}"
o4 = f"{max_cx // 180} {max_cy // 180}"
ol = [o1]
if o2 not in ol:
ol.append(o2)
@@ -122,7 +122,7 @@ def info_range(r1: tuple, r2: tuple) -> None:
for z in lvz:
for y in lvy:
for x in lvx:
print(f"{x//32}.{y//32}.{z}/{x}.{y}.{z}.map", end=" ")
print(f"{x // 32}.{y // 32}.{z}/{x}.{y}.{z}.map", end=" ")
print("")
@@ -234,10 +234,10 @@ Coordinate: \"x'(0->179) y'(0->179)\" or \"x'(0->179) y'(0->179) z\"
cx, cy, cz = retInfo
print(
f" Map: {cx//180}'{cx - 180 * (cx//180)}"
f" {cy//180}'{cy- 180 * (cy//180)} {cz}"
f" Map: {cx // 180}'{cx - 180 * (cx // 180)}"
f" {cy // 180}'{cy - 180 * (cy // 180)} {cz}"
)
print(f" File: {cx//32}.{cy//32}.{cz}/{cx}.{cy}.{cz}.map")
print(f" File: {cx // 32}.{cy // 32}.{cz}/{cx}.{cy}.{cz}.map")
info_folder(f"{cx//32}.{cy//32}.{cz}")
info_folder(f"{cx // 32}.{cy // 32}.{cz}")
+1 -1
View File
@@ -329,7 +329,7 @@ class Handler:
row = int(_map.split('.')[0])
column = int(_map.split('.')[1])
folder = pathlib.Path.joinpath(self.maps_folder,
f'{row//32}.{column//32}.0')
f'{row // 32}.{column // 32}.0')
if not self.dry_run:
folder.mkdir(parents=True, exist_ok=True)
+6 -3
View File
@@ -298,7 +298,8 @@ class Kernel32Wrapper:
@staticmethod
def create_buffer(obj: Any, max_buffer_len: Optional[int] = None) -> str:
"""Creates a ctypes unicode buffer given an object convertible to string.
"""Creates a ctypes unicode buffer given an object convertible to
string.
Args:
obj: The object from which to create a buffer. Must be convertible
@@ -407,7 +408,8 @@ class ProcessLimiter:
def _query_information_job_object(self, structure: ctypes.Structure,
query_type: int) -> ctypes.Structure:
"""[Internal] Retrieves limit and job state information from the job object.
"""[Internal] Retrieves limit and job state information from the job
object.
Args:
structure: The limit or job state information.
@@ -599,7 +601,8 @@ class ProcessLimiter:
self._handle_process = handle_process
def limit_process_memory(self, memory_limit: int) -> None:
"""Effectively limit the process memory that the target process can allocates.
"""Effectively limit the process memory that the target process can
allocates.
Args:
memory_limit: The memory limit of the process, in MiB (MebiBytes).
+3 -3
View File
@@ -81,7 +81,7 @@ def tile_convert(otile, main_id, new_tile_number):
for g in ('fg', 'bg'):
if g not in otile:
continue
if type(otile[g]) == int:
if type(otile[g]) is int:
if otile[g] == -1:
continue
otile[g] = list([otile[g]])
@@ -162,9 +162,9 @@ def tile_convert(otile, main_id, new_tile_number):
for tile in ntile[g]:
# if tile_num is a dict with "weight" and "sprite",
# take the "sprite" number
if type(tile) == dict and "sprite" in tile:
if type(tile) is dict and "sprite" in tile:
iso_ize(tile["sprite"])
elif type(tile) == int:
elif type(tile) is int:
iso_ize(tile)
else:
raise RuntimeError("Unexpected sprite number: %s" % tile)