Skip to content

Commit f1e2895

Browse files
authored
Code style improvements (ruff, refurb) (#10)
1 parent e6cc1ae commit f1e2895

12 files changed

+91
-55
lines changed

changetext/changetext.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,5 +19,5 @@ def change_text(text):
1919
@log_exceptions()
2020
def outer_change_text(text):
2121
result = change_text(text)
22-
get_logger().write("{}({!r}) -> {!r}".format(outer_change_text.__name__, text, result))
22+
get_logger().write(f"{outer_change_text.__name__}({text!r}) -> {result!r}")
2323
return result

changetext/common_state.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,6 @@ def init():
1616
pass
1717

1818

19-
@functools.lru_cache()
19+
@functools.lru_cache
2020
def get_state(object_id=None):
2121
return ChangeTextState(object_id)

changetext/corrector.py

+7-5
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
class CorrectorRegistry:
88
def __init__(self):
9-
self.changes = list()
9+
self.changes = []
1010

1111
def register(self, regex=None, predicate=None):
1212
def decorator(func):
@@ -16,10 +16,12 @@ def decorator(func):
1616
if isinstance(regex, str):
1717
regex = re.compile(regex)
1818

19-
predicate = lambda text: regex.search(text)
19+
def predicate(text):
20+
return regex.search(text)
2021

2122
if predicate is None:
22-
predicate = lambda _text: True
23+
def predicate(_text):
24+
return True
2325

2426
self.changes.append((predicate, func))
2527

@@ -40,7 +42,7 @@ def incremental_changes(self, text):
4042
if predicate_result:
4143
result = func(text, predicate_result)
4244
if result:
43-
get_logger().write("{}({!r}) -> {!r}".format(func.__name__, text, result))
45+
get_logger().write(f"{func.__name__}({text!r}) -> {result!r}")
4446
text = result or text
4547

4648
return text
@@ -51,7 +53,7 @@ def exclusive_changes(self, text):
5153
if predicate_result:
5254
result = func(text, predicate_result)
5355
if result:
54-
get_logger().write("{}({!r}) -> {!r}".format(func.__name__, text, result))
56+
get_logger().write(f"{func.__name__}({text!r}) -> {result!r}")
5557
return result or text
5658

5759
return text

changetext/final_changes.py

+24-24
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@
4646

4747
@final_changes.register(regex=r"Histories of (\w+) and (\w+)")
4848
def corr_histories_of(_, search_result):
49-
return "Истории о{} и {}".format(histories_adjs[search_result.group(1)], histories_adjs[search_result.group(2)])
49+
return f"Истории о{histories_adjs[search_result.group(1)]} и {histories_adjs[search_result.group(2)]}"
5050

5151

5252
possessive_adjectives = {"жаба": "жабий", "корова": "коровий", "медведь": "медвежий"}
@@ -117,7 +117,7 @@ def corr_container(text, _):
117117
adjective = None
118118
gender = get_gender(container, {"nomn"})
119119
adjective = inflect_adjective(adjective, gender)
120-
replacement_string = "{} {} ({})".format(container, containment, adjective)
120+
replacement_string = f"{container} {containment} ({adjective})"
121121
else:
122122
words = of_material.split()
123123
material = None
@@ -144,7 +144,7 @@ def corr_container(text, _):
144144
material = "из " + " ".join(gen_case)
145145
else:
146146
material = of_material
147-
replacement_string = "{} {} ({}".format(container, containment, material)
147+
replacement_string = f"{container} {containment} ({material}"
148148
if initial_string[-1] == ")":
149149
replacement_string += ")"
150150
text = text.replace(initial_string, replacement_string.capitalize())
@@ -245,7 +245,7 @@ def corr_of_material_item(text, _):
245245
else:
246246
replacement_string = " ".join(words) + " " + of_material
247247
else:
248-
raise ValueError("Unknown case: {!r}".format(text))
248+
raise ValueError(f"Unknown case: {text!r}")
249249

250250
text = text.replace(initial_string, replacement_string)
251251
return text
@@ -282,7 +282,7 @@ def corr_clothes(text, _):
282282
search_result = re_clothes.search(text)
283283
text = text.replace(
284284
search_result.group(1),
285-
"{} {} {}".format(search_result.group(4), search_result.group(3), to_genitive_case(search_result.group(2))),
285+
f"{search_result.group(4)} {search_result.group(3)} {to_genitive_case(search_result.group(2))}",
286286
)
287287
text = text.replace("левый", "левая")
288288
text = text.replace("правый", "правая")
@@ -307,7 +307,7 @@ def corr_prepared(text, search_result):
307307
# >>> corr_prepared(" рубленная гигантский крот лёгкие")
308308
# ' рубленные лёгкие гигантского крота'
309309
groups = search_result.groups()
310-
result = text.replace(groups[0], "{} {} {}".format(groups[1], groups[3], to_genitive_case(groups[2])))
310+
result = text.replace(groups[0], f"{groups[1]} {groups[3]} {to_genitive_case(groups[2])}")
311311
return result
312312

313313

@@ -414,14 +414,14 @@ def corr_weapon_trap_parts(text, search_result):
414414
gender = get_main_word_gender(obj)
415415
new_adj = inflect_as_adjective(adj, gender)
416416
new_word_2 = inflect_adjective(make_adjective[material], gender)
417-
text = text.replace(search_result.group(0), "{} {} {}".format(new_adj, new_word_2, obj))
417+
text = text.replace(search_result.group(0), f"{new_adj} {new_word_2} {obj}")
418418
else:
419419
material = " ".join(words[:3])
420420
obj = " ".join(words[3:])
421421
gender = get_main_word_gender(obj)
422422
assert gender is not None
423423
new_adj = inflect_as_adjective(adj, gender)
424-
text = text.replace(search_result.group(0), "{} {} {}".format(new_adj, obj, material))
424+
text = text.replace(search_result.group(0), f"{new_adj} {obj} {material}")
425425
return text
426426

427427

@@ -632,7 +632,7 @@ def corr_stopped_construction(_, search_result):
632632
else:
633633
gen_case_obj = to_genitive_case(obj)
634634

635-
return ("{} приостановили строительство {}.".format(subj, gen_case_obj)).capitalize()
635+
return f"{subj} приостановили строительство {gen_case_obj}.".capitalize()
636636

637637

638638
@final_changes.register(
@@ -655,7 +655,7 @@ def corr_relief(_, search_result):
655655
if group1.split(" ")[0] == "Мёртвый":
656656
text = "Мёртвое деревце ({})".format("".join(search_result.group(0).split(" ")[1:-1]))
657657
else:
658-
text = "Деревце ({})".format(group1)
658+
text = f"Деревце ({group1})"
659659
return text.capitalize()
660660

661661
if " " in group1:
@@ -688,7 +688,7 @@ def corr_relief(_, search_result):
688688
text = "{} {} из {}".format(" ".join(first_words), obj, " ".join(words))
689689
else:
690690
material = group1
691-
text = "{} из {}".format(obj, to_genitive_case(material))
691+
text = f"{obj} из {to_genitive_case(material)}"
692692

693693
if "иза" in text:
694694
text = text.replace(" иза", "")
@@ -722,7 +722,7 @@ def corr_adjective_relief(text, search_result):
722722
gender = get_gender(obj)
723723
new_word = inflect_adjective(adjective, gender, "nomn")
724724
if new_word:
725-
text = "{} {}".format(new_word, obj)
725+
text = f"{new_word} {obj}"
726726

727727
return text.capitalize()
728728

@@ -787,7 +787,7 @@ def corr_settlement(_, search_result):
787787
name = search_result.group(3)
788788

789789
if len(adjective) == 0:
790-
return "{} {}".format(settlement.capitalize(), name.capitalize())
790+
return f"{settlement.capitalize()} {name.capitalize()}"
791791

792792
if adjective in {"Покинуть", "Разрушить"}:
793793
return
@@ -802,7 +802,7 @@ def corr_settlement(_, search_result):
802802
if adjective_2 is None:
803803
adjective_2 = adjective
804804

805-
return "{} {} {}".format(adjective_2.capitalize(), settlement, name.capitalize())
805+
return f"{adjective_2.capitalize()} {settlement} {name.capitalize()}"
806806

807807

808808
# Clothier's shop
@@ -845,7 +845,7 @@ def corr_clothiers_shop(_, search_result):
845845
preposition = "на"
846846
material = inflect_noun(material, case="loct", orig_form={"nomn"})
847847

848-
return "{} {} {} {}".format(verb, product, preposition, material)
848+
return f"{verb} {product} {preposition} {material}"
849849
else:
850850
if product in {"щит", "баклер"}:
851851
_, of_material = cloth_subst[material] # Don't change the verb, leave 'Делать'/'Изготовить'
@@ -860,9 +860,9 @@ def corr_clothiers_shop(_, search_result):
860860
if material in make_adjective: # "шёлк" -> "шёлковый"
861861
gender = get_gender(product, {"nomn"})
862862
material_adj = inflect_adjective(make_adjective[material], gender, "accs", animated=False)
863-
return "{} {} {}".format(verb, material_adj, product_accus) # {Шить} {шёлковую} {робу}
863+
return f"{verb} {material_adj} {product_accus}" # {Шить} {шёлковую} {робу}
864864
else:
865-
return "{} {} {}".format(verb, product_accus, of_material) # {Шить} {робу} {из ткани}
865+
return f"{verb} {product_accus} {of_material}" # {Шить} {робу} {из ткани}
866866

867867

868868
@final_changes.register(regex=r"(Делать|Изготовить|Украшать)([\w\s/]+)$")
@@ -903,7 +903,7 @@ def corr_craft_general(text, search_result):
903903
if len(words) == 1 and words[0] not in make_adjective and not is_adjective(words[0]):
904904
material = inflect_noun(words[0], "gent", orig_form={"nomn", "inan"}) # рог -> (из) рога
905905
assert material is not None
906-
result = "{} {} из {}".format(verb, product, material)
906+
result = f"{verb} {product} из {material}"
907907
else:
908908
adjectives = [
909909
make_adjective[word] if word in make_adjective else word if is_adjective(word) else None
@@ -913,7 +913,7 @@ def corr_craft_general(text, search_result):
913913
adjectives = [inflect_adjective(adj, product_gender, "accs", animated=False) for adj in adjectives]
914914
result = "{} {} {}".format(verb, " ".join(adjectives), product)
915915
else:
916-
result = "{} {}".format(verb, product)
916+
result = f"{verb} {product}"
917917

918918
return text.replace(search_result.group(0), result).capitalize()
919919

@@ -962,7 +962,7 @@ def corr_animal_material(_, search_result):
962962
def corr_rings(text, search_result):
963963
obj = search_result.group(2)
964964
description = search_result.group(1)
965-
return text.replace(search_result.group(0), "{} из {}".format(obj, to_genitive_case(description)))
965+
return text.replace(search_result.group(0), f"{obj} из {to_genitive_case(description)}")
966966

967967

968968
@final_changes.register(predicate=lambda text: text.startswith("Вы нашли из "))
@@ -983,7 +983,7 @@ def corr_you_struck(text, _):
983983
else:
984984
result = inflect_collocation(material, {"accs"})
985985

986-
return "{} {}!".format(you_struck, result)
986+
return f"{you_struck} {result}!"
987987

988988

989989
@final_changes.register(regex=r"(.+)\s(стал)\s(.+)\.")
@@ -1005,6 +1005,6 @@ def corr_become(_, search_result):
10051005
words = search_result.group(3)
10061006
words = inflect_collocation(words, {"ablt"})
10071007
if subj.startswith("Животное"):
1008-
return "Животное выросло и стало {}.".format(words)
1009-
else:
1010-
return "{} {} {}.".format(subj, verb, words)
1008+
return f"Животное выросло и стало {words}."
1009+
1010+
return f"{subj} {verb} {words}."

changetext/logging_tools.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ def write(self, text):
2424
self.logged.add(text)
2525

2626

27-
@functools.lru_cache()
27+
@functools.lru_cache
2828
def get_logger(stream=None):
2929
return LoggerWrapper(stream)
3030

@@ -36,7 +36,7 @@ def wrapper(text):
3636
try:
3737
return func(text)
3838
except Exception:
39-
get_logger(stream).logger.exception("An exception occurred. Initial string: {!r}".format(text))
39+
get_logger(stream).logger.exception(f"An exception occurred. Initial string: {text!r}")
4040

4141
return wrapper
4242

changetext/preliminary_changes.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ def corr_ending_s(text):
9191
number = int(number)
9292
parse = [x for x in custom_parse(group2) if {"NOUN", "nomn", "sing"} in x.tag]
9393
assert len(parse) == 1
94-
replacement_string = "{:d} {}".format(number, parse[0].make_agree_with_number(number).word)
94+
replacement_string = f"{number:d} {parse[0].make_agree_with_number(number).word}"
9595
elif group2 in dict_ending_s:
9696
replacement_string = dict_ending_s[group2]
9797
elif " " not in group2:
@@ -236,8 +236,8 @@ def corr_animal_gender(text, search_result):
236236
animal = search_result.group(1)
237237
if animal not in animal_genders:
238238
return None
239-
else:
240-
return text.replace(search_result.group(0), animal_genders[animal][gender] + ", " + search_result.group(2))
239+
240+
return text.replace(search_result.group(0), animal_genders[animal][gender] + ", " + search_result.group(2))
241241

242242

243243
@preliminary_changes.register(regex=re.compile(r"(он|она|вы)\s+(не\s+)?(имеете?)", flags=re.IGNORECASE))
@@ -320,7 +320,7 @@ def corr_tags_outer(text, _):
320320
try:
321321
result = corr_tags(text)
322322
except (AssertionError, ValueError) as err:
323-
print("corr_tags() raises exception {!r}:".format(err))
323+
print(f"corr_tags() raises exception {err!r}:")
324324
print(traceback.format_exc())
325325
result = " ".join(
326326
part.strip(" ") if not part.startswith("<") else part.strip("<>").partition(":")[2]

changetext/tag_correction.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def corr_tags(text, state=None):
5454

5555
if "get-form" in tags:
5656
if get_index is not None:
57-
raise ValueError("Duplicate <get-form> tag in {!r}".format(text))
57+
raise ValueError(f"Duplicate <get-form> tag in {text!r}")
5858
get_index = len(text_parts)
5959
tags.remove("get-form")
6060
elif "set-form" in tags:

changetext/utf16_codec.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ def wrapper(data):
88
data = data.decode("utf-16-le")
99
output = func(data)
1010
return output if output is None else output.encode("utf-16-le") + b"\0\0"
11-
else:
12-
return func(data)
11+
12+
return func(data)
1313

1414
return wrapper

changetext/utils.py

+12-12
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,12 @@
1212
def custom_parse(word: str) -> List[Parse]:
1313
if word.lower().startswith("адамантин"):
1414
return morph.parse(word) # Pymorphy2 thinks that adamantine is a surname and treats it properly
15-
else:
16-
return [p for p in morph.parse(word) if all(tag not in p.tag for tag in unwanted_tags)]
15+
16+
return [p for p in morph.parse(word) if all(tag not in p.tag for tag in unwanted_tags)]
1717

1818

1919
def tag_to_set(tag: OpencorporaTag) -> Set[str]:
20-
return set(sum((ss.split() for ss in str(tag).split(",")), list()))
20+
return set(sum((ss.split() for ss in str(tag).split(",")), []))
2121

2222

2323
def common_tags(parse: List[Parse]) -> Set[str]:
@@ -65,7 +65,7 @@ def inflect_collocation(text: str, tags: Set[str]) -> str:
6565
for i, word in enumerate(words[:j]):
6666
parse = custom_parse(word)
6767
if not is_adjective(word, parse):
68-
raise ValueError("{} is not an adjective".format(word))
68+
raise ValueError(f"{word} is not an adjective")
6969
p = next(p for p in parse if {"ADJF"} in p.tag)
7070
p1 = p.inflect(tags)
7171
assert p1 is not None, (p, tags)
@@ -90,8 +90,8 @@ def split_sentence(text: str) -> Optional[Tuple[str, str]]:
9090
sentence = re_sentence.search(text)
9191
if sentence:
9292
return cast(Tuple[str, str], sentence.groups())
93-
else:
94-
return text, ""
93+
94+
return text, ""
9595

9696

9797
def is_enumeration_delimiter(text: str) -> bool:
@@ -410,7 +410,7 @@ def get_gender(obj: str, known_tags: Union[None, str, Set[str]] = None) -> Optio
410410
if obj.lower() in gender_exceptions:
411411
return gender_exceptions[obj.lower()]
412412
else:
413-
if len(parse) > 0:
413+
if parse:
414414
gender = pm_gender(parse[0])
415415
for p in parse:
416416
if pm_gender(p) != gender:
@@ -433,7 +433,7 @@ def get_main_word_gender(text: str) -> Optional[str]:
433433

434434
def parse_as_adjective(adjective: str) -> List[Parse]:
435435
parse = [p for p in custom_parse(adjective) if "ADJF" in p.tag or "PRTF" in p.tag]
436-
assert len(parse) > 0, "parse: {!r}".format(parse)
436+
assert parse, f"parse: {parse!r}"
437437
return parse
438438

439439

@@ -466,7 +466,7 @@ def inflect_noun(word: str, case: str, orig_form: Union[None, str, Set[str]] = N
466466
if orig_form:
467467
parse = [p for p in parse if orig_form in p.tag]
468468

469-
assert len(parse) > 0
469+
assert parse
470470

471471
p = parse[0]
472472
new_form = p.inflect({case, p.tag.number})
@@ -477,8 +477,8 @@ def inflect_noun(word: str, case: str, orig_form: Union[None, str, Set[str]] = N
477477
def to_genitive_case_single_noun(word: str) -> str:
478478
if word.lower() in gent_case_except:
479479
return gent_case_except[word.lower()]
480-
else:
481-
return inflect_noun(word, case="gent")
480+
481+
return inflect_noun(word, case="gent")
482482

483483

484484
def to_genitive_case_list(words: List[str]) -> Iterator[str]:
@@ -516,7 +516,7 @@ def inflect_as_adjective(adj: str, gender: str) -> str:
516516
elif is_adjective(adj):
517517
new_adj = inflect_adjective(adj, gender)
518518
else:
519-
raise ValueError("Cannot inflect {} as adjective".format(adj))
519+
raise ValueError(f"Cannot inflect {adj} as adjective")
520520

521521
return new_adj
522522

0 commit comments

Comments
 (0)