Skip to content

Commit 52892e5

Browse files
committed
Update type hints for Python >= 3.9
- Use standard collections, e.g. list[str] instead of typing.List[str]. - Import certain types from collections.abc, instead of deprecated aliases in typing. - Omit .model.transport, handled in #225.
1 parent cc13635 commit 52892e5

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

50 files changed

+188
-188
lines changed

message_ix_models/model/build.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import logging
2-
from typing import Callable, Dict, List, Mapping, Optional, Union
2+
from collections.abc import Callable, Mapping
3+
from typing import Optional, Union
34

45
import ixmp
56
import pandas as pd
@@ -77,7 +78,7 @@ def apply_spec( # noqa: C901
7778
pass
7879
maybe_check_out(scenario)
7980

80-
dump: Dict[str, pd.DataFrame] = {} # Removed data
81+
dump: dict[str, pd.DataFrame] = {} # Removed data
8182

8283
# Sort the list of sets by the number of dimensions; this places basic (non-indexed)
8384
# sets first. Elements for these sets must be added before elements for indexed
@@ -166,7 +167,7 @@ def apply_spec( # noqa: C901
166167
)
167168

168169

169-
def ellipsize(elements: List) -> str:
170+
def ellipsize(elements: list) -> str:
170171
"""Generate a short string representation of `elements`.
171172
172173
If the list has more than 5 elements, only the first two and last two are shown,

message_ix_models/model/disutility.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import logging
22
from collections import defaultdict
3+
from collections.abc import Mapping, MutableMapping, Sequence
34
from copy import copy
45
from functools import partial
56
from itertools import product
6-
from typing import List, Mapping, MutableMapping, Sequence
77

88
import message_ix
99
import pandas as pd
@@ -166,10 +166,10 @@ def data_conversion(info, spec: Spec) -> MutableMapping[str, pd.DataFrame]:
166166
)
167167

168168
# Use the spec to retrieve information
169-
technology: List[Code] = spec.add.set["technology"]
169+
technology: list[Code] = spec.add.set["technology"]
170170

171171
# Data to return
172-
data0: Mapping[str, List[pd.DataFrame]] = defaultdict(list)
172+
data0: Mapping[str, list[pd.DataFrame]] = defaultdict(list)
173173

174174
# Loop over conversion technologies
175175
for t in technology:

message_ix_models/model/emissions.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import logging
22
import re
3-
from typing import Optional, Tuple
3+
from typing import Optional
44

55
import pandas as pd
66
from genno import Quantity
@@ -153,7 +153,7 @@ def add_tax_emission(
153153
scen.add_par(name, data)
154154

155155

156-
def split_species(unit_expr: str) -> Tuple[str, Optional[str]]:
156+
def split_species(unit_expr: str) -> tuple[str, Optional[str]]:
157157
"""Split `unit_expr` to an expression without a unit mention, and maybe species."""
158158
if match := re.fullmatch("(.*)(CO2|C)(.*)", unit_expr):
159159
return f"{match.group(1)}{match.group(3)}", match.group(2)

message_ix_models/model/macro.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,11 @@
55
"""
66

77
import logging
8+
from collections.abc import Mapping
89
from functools import lru_cache
910
from itertools import product
1011
from pathlib import Path
11-
from typing import TYPE_CHECKING, List, Literal, Mapping, Optional, Union
12+
from typing import TYPE_CHECKING, Literal, Optional, Union
1213

1314
import pandas as pd
1415

@@ -29,7 +30,7 @@
2930
def generate(
3031
parameter: Literal["aeei", "config", "depr", "drate", "lotol"],
3132
context: "Context",
32-
commodities: Union[List[str], List["Code"]] = COMMODITY,
33+
commodities: Union[list[str], list["Code"]] = COMMODITY,
3334
value: Optional[float] = None,
3435
) -> pd.DataFrame:
3536
"""Generate uniform data for one :mod:`message_ix.macro` `parameter`.

message_ix_models/model/material/build.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import logging
2-
from typing import Any, Dict, Mapping
2+
from collections.abc import Mapping
3+
from typing import Any
34

45
import message_ix
56
import pandas as pd
@@ -206,7 +207,7 @@ def get_spec() -> Mapping[str, ScenarioInfo]:
206207

207208

208209
def make_spec(regions: str, materials: str or None = SPEC_LIST) -> Spec:
209-
sets: Dict[str, Any] = dict()
210+
sets: dict[str, Any] = dict()
210211
materials = ["common"] if not materials else materials
211212
# Overrides specific to regional versions
212213
tmp = dict()

message_ix_models/model/material/data_aluminum.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from collections import defaultdict
2-
from typing import Dict, Iterable, List
2+
from collections.abc import Iterable
33

44
import message_ix
55
import pandas as pd
@@ -69,7 +69,7 @@ def read_data_aluminum(
6969
return data_alu, data_alu_rel, data_aluminum_ts
7070

7171

72-
def gen_data_alu_ts(data: pd.DataFrame, nodes: list) -> Dict[str, pd.DataFrame]:
72+
def gen_data_alu_ts(data: pd.DataFrame, nodes: list) -> dict[str, pd.DataFrame]:
7373
"""
7474
Generates time variable parameter data for aluminum sector
7575
Parameters
@@ -330,7 +330,7 @@ def gen_data_alu_const(
330330
glb_reg: str,
331331
years: Iterable,
332332
yv_ya: pd.DataFrame,
333-
nodes: List[str],
333+
nodes: list[str],
334334
):
335335
results = defaultdict(list)
336336
for t in config["technology"]["add"]:
@@ -544,7 +544,7 @@ def gen_mock_demand_aluminum(scenario: message_ix.Scenario) -> pd.DataFrame:
544544
return demand2020_al
545545

546546

547-
def gen_data_alu_trade(scenario: message_ix.Scenario) -> Dict[str, pd.DataFrame]:
547+
def gen_data_alu_trade(scenario: message_ix.Scenario) -> dict[str, pd.DataFrame]:
548548
results = defaultdict(list)
549549

550550
data_trade = pd.read_csv(

message_ix_models/model/material/data_methanol.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from ast import literal_eval
2-
from typing import TYPE_CHECKING, Dict, List
2+
from typing import TYPE_CHECKING
33

44
import pandas as pd
55
import yaml
@@ -30,7 +30,7 @@
3030
}
3131

3232

33-
def gen_data_methanol(scenario: "Scenario") -> Dict[str, pd.DataFrame]:
33+
def gen_data_methanol(scenario: "Scenario") -> dict[str, pd.DataFrame]:
3434
"""
3535
Generates data for methanol industry model
3636
@@ -94,8 +94,8 @@ def gen_data_methanol(scenario: "Scenario") -> Dict[str, pd.DataFrame]:
9494
def broadcast_nodes(
9595
df_bc_node: pd.DataFrame,
9696
df_final: pd.DataFrame,
97-
node_cols: List[str],
98-
node_cols_codes: Dict[str, pd.Series],
97+
node_cols: list[str],
98+
node_cols_codes: dict[str, pd.Series],
9999
i: int,
100100
) -> pd.DataFrame:
101101
"""
@@ -105,8 +105,8 @@ def broadcast_nodes(
105105
----------
106106
df_bc_node: pd.DataFrame
107107
df_final: pd.DataFrame
108-
node_cols: List[str]
109-
node_cols_codes: Dict[str, pd.Series]
108+
node_cols: list[str]
109+
node_cols_codes: dict[str, pd.Series]
110110
i: int
111111
"""
112112
if len(node_cols) == 1:
@@ -153,17 +153,17 @@ def broadcast_nodes(
153153

154154
def broadcast_years(
155155
df_bc_node: pd.DataFrame,
156-
yr_col_out: List[str],
157-
yr_cols_codes: Dict[str, List[str]],
156+
yr_col_out: list[str],
157+
yr_cols_codes: dict[str, list[str]],
158158
col: str,
159159
) -> pd.DataFrame:
160160
"""
161161
Broadcast years that were stored in pivoted row
162162
Parameters
163163
----------
164164
df_bc_node: pd.DataFrame
165-
yr_col_out: List[str]
166-
yr_cols_codes: ict[str, List[str]]
165+
yr_col_out: list[str]
166+
yr_cols_codes: ict[str, list[str]]
167167
col: str
168168
"""
169169
if len(yr_col_out) == 1:

message_ix_models/model/material/data_petro.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
from collections import defaultdict
2-
from typing import List, Set
32

43
import message_ix
54
import pandas as pd
@@ -166,7 +165,7 @@ def get_demand_t1_with_income_elasticity(
166165

167166

168167
def gen_data_petro_ts(
169-
data_petro_ts: pd.DataFrame, results: dict[list], tec_ts: Set[str], nodes: List[str]
168+
data_petro_ts: pd.DataFrame, results: dict[list], tec_ts: set[str], nodes: list[str]
170169
) -> None:
171170
for t in tec_ts:
172171
common = dict(
@@ -239,7 +238,7 @@ def assign_input_outpt(
239238
rg: str,
240239
global_region: str,
241240
common: dict,
242-
nodes: List[str],
241+
nodes: list[str],
243242
) -> pd.DataFrame:
244243
com = split[1]
245244
lev = split[2]
@@ -295,7 +294,7 @@ def assign_input_outpt(
295294
return df
296295

297296

298-
def broadcast_to_regions(df: pd.DataFrame, global_region: str, nodes: List[str]):
297+
def broadcast_to_regions(df: pd.DataFrame, global_region: str, nodes: list[str]):
299298
if "node_loc" in df.columns:
300299
if (
301300
len(set(df["node_loc"])) == 1

message_ix_models/model/material/data_steel.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from collections import defaultdict
2-
from typing import Dict, Iterable, List
2+
from collections.abc import Iterable
33

44
import message_ix
55
import pandas as pd
@@ -119,7 +119,7 @@ def gen_mock_demand_steel(scenario: message_ix.Scenario) -> pd.DataFrame:
119119

120120

121121
def gen_data_steel_ts(
122-
data_steel_ts: pd.DataFrame, results: Dict[str, list], t: str, nodes: List[str]
122+
data_steel_ts: pd.DataFrame, results: dict[str, list], t: str, nodes: list[str]
123123
):
124124
common = dict(
125125
time="year",
@@ -213,11 +213,11 @@ def gen_data_steel_ts(
213213

214214
def get_data_steel_const(
215215
data_steel: pd.DataFrame,
216-
results: Dict[str, list],
216+
results: dict[str, list],
217217
params: Iterable,
218218
t: str,
219219
yv_ya: pd.DataFrame,
220-
nodes: List[str],
220+
nodes: list[str],
221221
global_region: str,
222222
):
223223
for par in params:

message_ix_models/model/material/data_util.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import os
2+
from collections.abc import Mapping
23
from functools import lru_cache
3-
from typing import TYPE_CHECKING, Literal, Mapping
4+
from typing import TYPE_CHECKING, Literal
45

56
import ixmp
67
import message_ix

message_ix_models/model/structure.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
import logging
22
import re
33
from collections import ChainMap
4+
from collections.abc import Mapping, MutableMapping
45
from copy import copy
56
from functools import lru_cache
67
from itertools import product
7-
from typing import Dict, List, Mapping, MutableMapping, Tuple
88

99
import click
1010
import pandas as pd
@@ -20,7 +20,7 @@
2020

2121

2222
@lru_cache()
23-
def codelists(kind: str) -> List[str]:
23+
def codelists(kind: str) -> list[str]:
2424
"""Return a valid IDs for code lists of `kind`.
2525
2626
Parameters
@@ -32,7 +32,7 @@ def codelists(kind: str) -> List[str]:
3232

3333

3434
@lru_cache()
35-
def get_codes(name: str) -> List[Code]:
35+
def get_codes(name: str) -> list[Code]:
3636
"""Return codes for the dimension/set `name` in MESSAGE-GLOBIOM scenarios.
3737
3838
The information is read from :file:`data/{name}.yaml`, e.g.
@@ -101,15 +101,15 @@ def get_codelist(name: str) -> Codelist:
101101

102102

103103
@lru_cache()
104-
def get_region_codes(codelist: str) -> List[Code]:
104+
def get_region_codes(codelist: str) -> list[Code]:
105105
"""Return the codes that are children of "World" in the specified `codelist`."""
106106
nodes = get_codes(f"node/{codelist}")
107107
return nodes[nodes.index(Code(id="World"))].child
108108

109109

110110
def generate_product(
111111
data: Mapping, name: str, template: Code
112-
) -> Tuple[List[Code], Dict[str, xr.DataArray]]:
112+
) -> tuple[list[Code], dict[str, xr.DataArray]]:
113113
"""Generates codes using a `template` by Cartesian product along ≥1 dimensions.
114114
115115
:func:`generate_set_elements` is called for each of the `dims`, and these values

message_ix_models/model/water/build.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import logging
2+
from collections.abc import Mapping
23
from functools import lru_cache, partial
3-
from typing import Mapping
44

55
import pandas as pd
66
from sdmx.model.v21 import Code

message_ix_models/model/water/data/demands.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
"""Prepare data for adding demands"""
22

33
import os
4-
from typing import TYPE_CHECKING, Literal, Sequence, Union
4+
from collections.abc import Sequence
5+
from typing import TYPE_CHECKING, Literal, Union
56

67
import numpy as np
78
import pandas as pd

message_ix_models/model/water/utils.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from collections import defaultdict
33
from functools import lru_cache
44
from itertools import product
5-
from typing import Optional, Tuple
5+
from typing import Optional
66

77
import numpy as np
88
import pandas as pd
@@ -125,13 +125,13 @@ def func(row: pd.Series):
125125

126126

127127
def map_yv_ya_lt(
128-
periods: Tuple[int, ...], lt: int, ya: Optional[int] = None
128+
periods: tuple[int, ...], lt: int, ya: Optional[int] = None
129129
) -> pd.DataFrame:
130130
"""All meaningful combinations of (vintage year, active year) given `periods`.
131131
132132
Parameters
133133
----------
134-
periods : Tuple[int, ...]
134+
periods : tuple[int, ...]
135135
A sequence of years.
136136
lt : int, lifetime
137137
ya : int, active year

message_ix_models/model/workflow.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""Common steps for workflows."""
22

33
from dataclasses import dataclass, field
4-
from typing import TYPE_CHECKING, Any, Dict, Optional
4+
from typing import TYPE_CHECKING, Any, Optional
55

66
from message_ix import Scenario
77

@@ -21,7 +21,7 @@ class Config(ConfigHelper):
2121

2222
#: Information on an optional, other scenario from which to copy demand data in
2323
#: :func:`solve` using :func:`transfer_demands`. Default: empty, do nothing.
24-
demand_scenario: Dict = field(default_factory=dict)
24+
demand_scenario: dict = field(default_factory=dict)
2525

2626
#: :obj:`True` to call :func:`.reserve_margin.res_marg.main` in :func:`solve`.
2727
reserve_margin: bool = True
@@ -31,7 +31,7 @@ class Config(ConfigHelper):
3131
#: To replicate the behaviour of the `macro_params` argument to
3232
#: :meth:`.engage.ScenarioRunner.run`, which in turn sets the `convergence_issues`
3333
#: argument to :meth:`.engage.ScenarioRunner.solve`, set max_adjustment to 0.1.
34-
solve: Dict[str, Any] = field(
34+
solve: dict[str, Any] = field(
3535
default_factory=lambda: dict(model="MESSAGE-MACRO", max_adjustment=0.2)
3636
)
3737

0 commit comments

Comments
 (0)