Skip to content

Commit 3036e0e

Browse files
committed
type hinting
1 parent 7ad6384 commit 3036e0e

13 files changed

Lines changed: 99 additions & 79 deletions

ukgrantmaking/management/commands/export.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@
33
from ukgrantmaking.models.funder import Funder, FunderNote, FunderTag
44
from ukgrantmaking.models.funder_year import FunderYear
55
from ukgrantmaking.models.grant import Grant
6-
from ukgrantmaking.views import export_all_data
6+
from ukgrantmaking.views import export_all_data_excel
77

88

9-
@click.group(invoke_without_command=False)
9+
@click.group()
1010
def main():
1111
pass
1212

@@ -15,11 +15,11 @@ def main():
1515
@click.argument("filename", type=click.Path())
1616
def grants(filename):
1717
models = [Grant]
18-
export_all_data(models, filename)
18+
export_all_data_excel(models, filename)
1919

2020

2121
@main.command()
2222
@click.argument("filename", type=click.Path())
2323
def funders(filename):
2424
models = [Funder, FunderYear, FunderTag, FunderNote]
25-
export_all_data(models, filename)
25+
export_all_data_excel(models, filename)

ukgrantmaking/utils/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ def batched(iterable, n: int = DEFAULT_BATCH_SIZE):
1919

2020

2121
def do_batched_update(
22-
model: models.Model,
22+
model: type[models.Model],
2323
iterable: Generator[Dict, None, None],
2424
unique_fields: list[str],
2525
update_fields: list[str],

ukgrantmaking/utils/funder_individuals_summary.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@
99
from ukgrantmaking.models.funder_utils import FUNDER_CATEGORIES
1010

1111

12-
def funder_individuals_summary(current_fy: FinancialYear, effective_date: datetime):
12+
def funder_individuals_summary(
13+
current_fy: FinancialYear, effective_date: datetime
14+
) -> pd.DataFrame:
1315
summary_individuals = (
1416
pd.DataFrame.from_records(
1517
Funder.objects.filter(

ukgrantmaking/utils/funder_over_time.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,13 @@
1111

1212
def funder_over_time(
1313
current_fy: FinancialYear,
14-
columns: list[tuple[str, str, models.Aggregate]],
14+
columns: list[tuple[str, str, type[models.Aggregate]]],
1515
effective_date: datetime,
1616
n: int = 100,
1717
n_years: int = 5,
1818
sortby: str = "-cy_scale",
1919
**filters,
20-
):
20+
) -> pd.DataFrame:
2121
orgs = funder_table(
2222
current_fy,
2323
[

ukgrantmaking/utils/funder_summary.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from ukgrantmaking.models.funder_utils import FUNDER_CATEGORIES
1010

1111

12-
def funder_summary(current_fy: FinancialYear, effective_date: datetime):
12+
def funder_summary(current_fy: FinancialYear, effective_date: datetime) -> pd.DataFrame:
1313
result = (
1414
pd.DataFrame.from_records(
1515
Funder.objects.filter(

ukgrantmaking/utils/funder_summary_by_size.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@
99
from ukgrantmaking.models.funder_utils import FUNDER_CATEGORIES
1010

1111

12-
def funder_summary_by_size(current_fy: FinancialYear, effective_date: datetime):
12+
def funder_summary_by_size(
13+
current_fy: FinancialYear, effective_date: datetime
14+
) -> pd.DataFrame:
1315
result = (
1416
pd.DataFrame.from_records(
1517
Funder.objects.filter(

ukgrantmaking/utils/funder_table.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@ def funder_table(
1717
n: int = 100,
1818
sortby: str = "-cy_scale",
1919
tag_children: Optional[list[str]] = None,
20-
spending_threshold: int = 25_000,
20+
spending_threshold: int | None = 25_000,
2121
**filters,
22-
):
22+
) -> pd.DataFrame:
2323
ascending = True
2424
if sortby.startswith("-"):
2525
sortby = sortby[1:]
@@ -227,11 +227,11 @@ def funder_table(
227227
]
228228
if not tag_children_df.empty:
229229
tag_categories = pd.crosstab(
230-
tag_children_df["funder_id"],
231-
tag_children_df["fundertag__parent"],
230+
index=tag_children_df["funder_id"],
231+
columns=tag_children_df["fundertag__parent"],
232232
values=tag_children_df["fundertag"],
233-
aggfunc=lambda x: "; ".join(x),
234-
)
233+
aggfunc=lambda x: "; ".join(x), # type: ignore
234+
) # type: ignore
235235
df = df.join(tag_categories, on="org_id", how="left")
236236
columns += tag_children
237237

ukgrantmaking/utils/funder_trend_over_time.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@
1111
def funder_trend_over_time(
1212
years: list[str],
1313
field: str,
14-
aggregation: models.Aggregate,
14+
aggregation: type[models.Aggregate],
1515
effective_date: datetime,
16-
):
16+
) -> pd.DataFrame:
1717
year_annotations = {}
1818
for year in years:
1919
year_annotations[year] = aggregation(

ukgrantmaking/utils/grant.py

Lines changed: 23 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@
145145
}
146146

147147

148-
def get_all_grants(current_fy: FinancialYear):
148+
def get_all_grants(current_fy: FinancialYear) -> pd.DataFrame:
149149
columns = [
150150
"grant_id",
151151
"funding_organisation_id",
@@ -366,7 +366,7 @@ def grant_table(
366366
columns: list[str] = DEFAULT_COLUMNS,
367367
n: int = 100,
368368
sortby: str = "-amount_awarded_GBP",
369-
):
369+
) -> pd.DataFrame:
370370
sort_ascending = True
371371
if sortby.startswith("-"):
372372
sortby = sortby[1:]
@@ -382,7 +382,7 @@ def grant_table(
382382
def grant_summary(
383383
df: pd.DataFrame,
384384
groupby: list[str] = ["category", "segment"],
385-
):
385+
) -> pd.DataFrame:
386386
summary = (
387387
df.groupby(groupby)
388388
.agg(**AGG_COLUMNS)
@@ -448,7 +448,7 @@ def grant_summary(
448448
total_key = tuple("Total" for k in groupby)
449449
if len(total_key) == 1:
450450
total_key = total_key[0]
451-
summary.loc[total_key, :] = total_row.loc[total_key]
451+
summary.loc[total_key, :] = total_row.loc[total_key] # type: ignore
452452

453453
summary = summary.rename(
454454
columns={
@@ -472,7 +472,7 @@ def grant_crosstab(
472472
groupby: list[str] = ["category", "segment"],
473473
column_field="amount_awarded_GBP_band",
474474
values_field="grant_id",
475-
):
475+
) -> pd.DataFrame:
476476
aggfunc = "count" if values_field == "grant_id" else "sum"
477477
summary = (
478478
pd.crosstab(
@@ -484,7 +484,7 @@ def grant_crosstab(
484484
.assign(
485485
Total=lambda x: x.sum(axis=1),
486486
)
487-
.mask(lambda x: x["Total"] == 0)
487+
.mask(lambda x: x["Total"] == 0) # type: ignore
488488
.dropna(how="all")
489489
)
490490

@@ -515,7 +515,7 @@ def grant_crosstab(
515515
total_key = tuple("Total" for k in groupby)
516516
if len(total_key) == 1:
517517
total_key = total_key[0]
518-
summary.loc[total_key, :] = total_row.loc[total_key]
518+
summary.loc[total_key, :] = total_row.loc[total_key] # type: ignore
519519

520520
if values_field in ("amount_awarded_GBP", "annual_amount"):
521521
summary = summary.divide(1_000_000).astype(float).round(1)
@@ -533,15 +533,15 @@ def grant_by_size(
533533
df: pd.DataFrame,
534534
groupby: list[str] = ["category", "segment"],
535535
**kwargs,
536-
):
536+
) -> pd.DataFrame:
537537
return grant_crosstab(df, groupby, column_field="amount_awarded_GBP_band", **kwargs)
538538

539539

540540
def grant_by_duration(
541541
df: pd.DataFrame,
542542
groupby: list[str] = ["category", "segment"],
543543
**kwargs,
544-
):
544+
) -> pd.DataFrame:
545545
return grant_crosstab(
546546
df, groupby, column_field="planned_dates_duration_band", **kwargs
547547
)
@@ -551,43 +551,45 @@ def recipient_types(
551551
df: pd.DataFrame,
552552
groupby: list[str] = ["category", "segment"],
553553
**kwargs,
554-
):
554+
) -> pd.DataFrame:
555555
return grant_crosstab(df, groupby, column_field="recipient_type", **kwargs)
556556

557557

558558
def recipients_by_size(
559559
df: pd.DataFrame,
560560
groupby: list[str] = ["category", "segment"],
561561
**kwargs,
562-
):
562+
) -> pd.DataFrame:
563563
return grant_crosstab(df, groupby, column_field="recipient_income_band", **kwargs)
564564

565565

566566
def recipients_by_scale(
567567
df: pd.DataFrame,
568568
groupby: list[str] = ["category", "segment"],
569569
**kwargs,
570-
):
570+
) -> pd.DataFrame:
571571
return grant_crosstab(df, groupby, column_field="recipient__scale", **kwargs)
572572

573573

574574
def grants_by_region(
575575
df: pd.DataFrame,
576576
groupby: list[str] = ["category", "segment"],
577577
**kwargs,
578-
):
578+
) -> pd.DataFrame:
579579
return grant_crosstab(df, groupby, column_field="region", **kwargs)
580580

581581

582582
def grants_by_country(
583583
df: pd.DataFrame,
584584
groupby: list[str] = ["category", "segment"],
585585
**kwargs,
586-
):
586+
) -> pd.DataFrame:
587587
return grant_crosstab(df, groupby, column_field="country", **kwargs)
588588

589589

590-
def explode_crosstab(df: pd.DataFrame, groupby: list[str], field: str, **kwargs):
590+
def explode_crosstab(
591+
df: pd.DataFrame, groupby: list[str], field: str, **kwargs
592+
) -> pd.DataFrame:
591593
ct = grant_crosstab(
592594
df[df[field].notnull()].explode(field).reset_index(),
593595
groupby,
@@ -608,7 +610,7 @@ def grants_by_who(
608610
df: pd.DataFrame,
609611
groupby: list[str] = ["category", "segment"],
610612
**kwargs,
611-
):
613+
) -> pd.DataFrame:
612614
field = "recipient__who"
613615
return explode_crosstab(
614616
df,
@@ -622,7 +624,7 @@ def grants_by_how(
622624
df: pd.DataFrame,
623625
groupby: list[str] = ["category", "segment"],
624626
**kwargs,
625-
):
627+
) -> pd.DataFrame:
626628
field = "recipient__how"
627629
return explode_crosstab(
628630
df,
@@ -636,7 +638,7 @@ def grants_by_what(
636638
df: pd.DataFrame,
637639
groupby: list[str] = ["category", "segment"],
638640
**kwargs,
639-
):
641+
) -> pd.DataFrame:
640642
field = "recipient__what"
641643
return explode_crosstab(
642644
df,
@@ -646,7 +648,7 @@ def grants_by_what(
646648
)
647649

648650

649-
def recipient_size_by_amount_awarded(df: pd.DataFrame, **kwargs):
651+
def recipient_size_by_amount_awarded(df: pd.DataFrame, **kwargs) -> pd.DataFrame:
650652
return grant_crosstab(
651653
df,
652654
["amount_awarded_GBP_band"],
@@ -655,7 +657,7 @@ def recipient_size_by_amount_awarded(df: pd.DataFrame, **kwargs):
655657
)
656658

657659

658-
def number_of_grants_by_recipient(df: pd.DataFrame):
660+
def number_of_grants_by_recipient(df: pd.DataFrame) -> pd.DataFrame:
659661
summary = (
660662
df.groupby("recipient_id")
661663
.agg(
@@ -698,7 +700,7 @@ def number_of_grants_by_recipient(df: pd.DataFrame):
698700
return summary
699701

700702

701-
def who_funds_with_who(df: pd.DataFrame, groupby: str = "segment"):
703+
def who_funds_with_who(df: pd.DataFrame, groupby: str = "segment") -> pd.DataFrame:
702704
wfww = pd.crosstab(
703705
df["recipient_id"],
704706
df[groupby],

ukgrantmaking/utils/text.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import re
2+
from typing import Any
23

34
import titlecase
45

@@ -7,7 +8,7 @@
78
SENTENCE_SPLIT = re.compile(r"(\. )")
89

910

10-
def title_exceptions(word, **kwargs):
11+
def title_exceptions(word: str, **kwargs) -> str | None:
1112
word_test = word.strip("(){}<>.")
1213

1314
# lowercase words
@@ -95,7 +96,7 @@ def title_exceptions(word, **kwargs):
9596
return None
9697

9798

98-
def to_titlecase(s, sentence=False):
99+
def to_titlecase(s: Any, sentence: bool = False) -> Any:
99100
if not isinstance(s, str):
100101
return s
101102

@@ -116,11 +117,11 @@ def to_titlecase(s, sentence=False):
116117
return s[0].upper() + s[1:]
117118

118119

119-
def regex_search(s, regex):
120+
def regex_search(s: str, regex: str) -> bool:
120121
return re.search(regex, s) is not None
121122

122123

123-
def list_to_string(items, sep=", ", final_sep=" and "):
124+
def list_to_string(items: Any, sep: str = ", ", final_sep: str = " and ") -> str:
124125
if isinstance(items, str):
125126
return items
126127
if isinstance(items, set):
@@ -134,7 +135,7 @@ def list_to_string(items, sep=", ", final_sep=" and "):
134135
return sep.join(items[0:-1]) + final_sep + items[-1]
135136

136137

137-
def clean_url(url):
138+
def clean_url(url: str | None) -> str | None:
138139
if not url:
139140
return None
140141
url = re.sub(r"(https?:)?//", "", url)
@@ -145,7 +146,7 @@ def clean_url(url):
145146
return url
146147

147148

148-
def working_url(url):
149+
def working_url(url: str | None) -> str | None:
149150
if not url:
150151
return None
151152
if url.startswith("http") and not url.startswith("//"):

0 commit comments

Comments
 (0)