Skip to content

Commit 38bbcfa

Browse files
committed
Update .model.transport 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.
1 parent 4780c5a commit 38bbcfa

File tree

21 files changed

+140
-154
lines changed

21 files changed

+140
-154
lines changed

message_ix_models/model/transport/base.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from functools import partial
44
from itertools import pairwise, product
55
from pathlib import Path
6-
from typing import TYPE_CHECKING, Any, List, Optional
6+
from typing import TYPE_CHECKING, Any, Optional
77

88
import genno
99
import numpy as np
@@ -423,7 +423,7 @@ def to_csv(
423423

424424

425425
def format_share_constraints(
426-
qty: "AnyQuantity", config: dict, *, kind: str, groupby: List[str] = []
426+
qty: "AnyQuantity", config: dict, *, kind: str, groupby: list[str] = []
427427
) -> pd.DataFrame:
428428
"""Produce values for :file:`ue_share_constraints.xlsx`.
429429

message_ix_models/model/transport/build.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import logging
44
from importlib import import_module
55
from pathlib import Path
6-
from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple
6+
from typing import TYPE_CHECKING, Any, Optional
77

88
import pandas as pd
99
from genno import Computer, KeyExistsError, Quantity, quote
@@ -179,7 +179,7 @@ def add_exogenous_data(c: Computer, info: ScenarioInfo) -> None:
179179
# Identify appropriate source keyword arguments for loading GDP and population data
180180
source = str(config.ssp)
181181
if config.ssp in SSP_2017:
182-
source_kw: Tuple[Dict[str, Any], ...] = (
182+
source_kw: tuple[dict[str, Any], ...] = (
183183
dict(measure="GDP", model="IIASA GDP"),
184184
dict(measure="POP", model="IIASA GDP"),
185185
)
@@ -471,7 +471,7 @@ def get_computer(
471471
def main(
472472
context: Context,
473473
scenario: Scenario,
474-
options: Optional[Dict] = None,
474+
options: Optional[dict] = None,
475475
**option_kwargs,
476476
):
477477
"""Build MESSAGEix-Transport on `scenario`.

message_ix_models/model/transport/config.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import logging
22
from dataclasses import InitVar, dataclass, field, replace
33
from enum import Enum
4-
from typing import TYPE_CHECKING, Dict, List, Literal, Optional, Tuple, Union
4+
from typing import TYPE_CHECKING, Literal, Optional, Union
55

66
import message_ix
77
from genno import Quantity
@@ -63,7 +63,7 @@ class Config(ConfigHelper):
6363
#: for transport modes *other than* LDV. See :func:`non_ldv.growth_new_capacity`.
6464
#: "* initial_*_up"
6565
#: Base value for growth constraints. These values are arbitrary.
66-
constraint: Dict = field(
66+
constraint: dict = field(
6767
default_factory=lambda: {
6868
"LDV growth_activity_lo": -0.0192,
6969
"LDV growth_activity_up": 0.0192 * 3.0,
@@ -93,7 +93,7 @@ class Config(ConfigHelper):
9393
#: 'updateTRPdata', with the comment "Original data from Sei (PAO)."
9494
#: - This probably refers to some source that gave relative costs of different
9595
#: buses, in PAO, for this year; it is applied across all years.
96-
cost: Dict = field(
96+
cost: dict = field(
9797
default_factory=lambda: {
9898
#
9999
"ldv nga": 0.85,
@@ -114,7 +114,7 @@ class Config(ConfigHelper):
114114
#: specified in the corresponding technology.yaml file.
115115
#:
116116
#: .. todo:: Read directly from technology.yaml
117-
demand_modes: List[str] = field(
117+
demand_modes: list[str] = field(
118118
default_factory=lambda: ["LDV", "2W", "AIR", "BUS", "RAIL"]
119119
)
120120

@@ -129,7 +129,7 @@ class Config(ConfigHelper):
129129
dummy_supply: bool = False
130130

131131
#: Various efficiency factors.
132-
efficiency: Dict = field(
132+
efficiency: dict = field(
133133
default_factory=lambda: {
134134
"*": 0.2,
135135
"hev": 0.2,
@@ -150,7 +150,7 @@ class Config(ConfigHelper):
150150
emission_relations: bool = True
151151

152152
#: Various other factors.
153-
factor: Dict = field(default_factory=dict)
153+
factor: dict = field(default_factory=dict)
154154

155155
#: If :obj:`True` (the default), do not record/preserve parameter data when removing
156156
#: set elements from the base model.
@@ -171,7 +171,7 @@ class Config(ConfigHelper):
171171
#:
172172
#: ``F ROAD``: similar to IEA “Future of Trucks” (2017) values; see
173173
#: .transport.freight. Alternately use 5.0, similar to Roadmap 2017 values.
174-
load_factor: Dict = field(
174+
load_factor: dict = field(
175175
default_factory=lambda: {
176176
"F ROAD": 10.0,
177177
"F RAIL": 10.0,
@@ -183,7 +183,7 @@ class Config(ConfigHelper):
183183

184184
#: Period in which LDV costs match those of a reference region.
185185
#: Dimensions: (node,).
186-
ldv_cost_catch_up_year: Dict = field(default_factory=dict)
186+
ldv_cost_catch_up_year: dict = field(default_factory=dict)
187187

188188
#: Method for calibrating LDV stock and sales:
189189
#:
@@ -193,7 +193,7 @@ class Config(ConfigHelper):
193193

194194
#: Tuples of (node, technology (transport mode), commodity) for which minimum
195195
#: activity should be enforced. See :func:`.non_ldv.bound_activity_lo`.
196-
minimum_activity: Dict[Tuple[str, Tuple[str, ...], str], float] = field(
196+
minimum_activity: dict[tuple[str, tuple[str, ...], str], float] = field(
197197
default_factory=dict
198198
)
199199

@@ -202,15 +202,15 @@ class Config(ConfigHelper):
202202
mode_share: str = "default"
203203

204204
#: List of modules containing model-building calculations.
205-
modules: List[str] = field(
205+
modules: list[str] = field(
206206
default_factory=lambda: (
207207
"groups demand freight ikarus ldv disutility non_ldv plot data"
208208
).split()
209209
)
210210

211211
#: Used by :func:`.get_USTIMES_MA3T` to map MESSAGE regions to U.S. census divisions
212212
#: appearing in MA³T.
213-
node_to_census_division: Dict = field(default_factory=dict)
213+
node_to_census_division: dict = field(default_factory=dict)
214214

215215
#: **Temporary** setting for the SSP 2024 project: indicates whether the base
216216
#: scenario used is a policy (carbon pricing) scenario, or not. This currently does
@@ -226,7 +226,7 @@ class Config(ConfigHelper):
226226
#:
227227
#: :mod:`.transport.build` and :mod:`.transport.report` code will respond to these
228228
#: settings in documented ways.
229-
project: Dict[str, Enum] = field(
229+
project: dict[str, Enum] = field(
230230
default_factory=lambda: dict(
231231
futures=FUTURES_SCENARIO.BASE, navigate=NAVIGATE_SCENARIO.REF
232232
)
@@ -236,7 +236,7 @@ class Config(ConfigHelper):
236236
scaling: float = 1.0
237237

238238
#: Mapping from nodes to other nodes towards which share weights should converge.
239-
share_weight_convergence: Dict = field(default_factory=dict)
239+
share_weight_convergence: dict = field(default_factory=dict)
240240

241241
#: Specification for the structure of MESSAGEix-Transport, processed from contents
242242
#: of :file:`set.yaml` and :file:`technology.yaml`.
@@ -282,7 +282,7 @@ class Config(ConfigHelper):
282282
#: space-delimited string (:py:`"module_a -module_b"`) or sequence of strings.
283283
#: Values prefixed with a hyphen (:py:`"-module_b"`) are *removed* from
284284
#: :attr:`.modules`.
285-
extra_modules: InitVar[Union[str, List[str]]] = None
285+
extra_modules: InitVar[Union[str, list[str]]] = None
286286

287287
#: Identifier of a Transport Futures scenario, used to update :attr:`project` via
288288
#: :meth:`.ScenarioFlags.parse_futures`.
@@ -315,7 +315,7 @@ def from_context(
315315
cls,
316316
context: Context,
317317
scenario: Optional[message_ix.Scenario] = None,
318-
options: Optional[Dict] = None,
318+
options: Optional[dict] = None,
319319
) -> "Config":
320320
"""Configure `context` for building MESSAGEix-Transport.
321321

message_ix_models/model/transport/data.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,11 @@
22

33
import logging
44
from collections import defaultdict
5+
from collections.abc import Callable, Mapping
56
from copy import deepcopy
67
from functools import partial
78
from operator import le
8-
from typing import TYPE_CHECKING, Callable, Dict, List, Mapping, Optional, Set, Tuple
9+
from typing import TYPE_CHECKING, Optional
910

1011
import pandas as pd
1112
from genno import Computer, Key, Quantity
@@ -51,8 +52,8 @@ def prepare_computer(c: Computer):
5152

5253

5354
def conversion(
54-
nodes: List[str], years: List[int], config: dict
55-
) -> Dict[str, pd.DataFrame]:
55+
nodes: list[str], years: list[int], config: dict
56+
) -> dict[str, pd.DataFrame]:
5657
"""Input and output data for conversion technologies:
5758
5859
The technologies are named 'transport {service} load factor'.
@@ -72,7 +73,7 @@ def conversion(
7273
("pax", 1.0, "Gp km / a"),
7374
]
7475

75-
data0: Mapping[str, List] = defaultdict(list)
76+
data0: Mapping[str, list] = defaultdict(list)
7677
for service, factor, output_unit in service_info:
7778
i_o = make_io(
7879
(f"transport {service} vehicle", "useful", "Gv km"),
@@ -98,7 +99,7 @@ def conversion(
9899
return data1
99100

100101

101-
def dummy_supply(technologies: List["Code"], info, config) -> Dict[str, pd.DataFrame]:
102+
def dummy_supply(technologies: list["Code"], info, config) -> dict[str, pd.DataFrame]:
102103
"""Dummy fuel supply for the bare RES."""
103104
if not config["transport"].dummy_supply:
104105
return dict()
@@ -116,7 +117,7 @@ def dummy_supply(technologies: List["Code"], info, config) -> Dict[str, pd.DataF
116117
else:
117118
raise TypeError(type(commodity))
118119

119-
result: Dict[str, pd.DataFrame] = dict()
120+
result: dict[str, pd.DataFrame] = dict()
120121
common = dict(mode="all", time="year", time_dest="year", unit="GWa")
121122
values = dict(output=1.0, var_cost=1.0)
122123

@@ -133,7 +134,7 @@ def dummy_supply(technologies: List["Code"], info, config) -> Dict[str, pd.DataF
133134
return result
134135

135136

136-
def misc(info: ScenarioInfo, nodes: List[str], y: List[int]):
137+
def misc(info: ScenarioInfo, nodes: list[str], y: list[int]):
137138
"""Miscellaneous bounds for calibration/vetting."""
138139

139140
# Limit activity of methanol LDVs in the model base year
@@ -157,8 +158,8 @@ def misc(info: ScenarioInfo, nodes: List[str], y: List[int]):
157158

158159

159160
def navigate_ele(
160-
nodes: List[str], techs: List["Code"], t_groups, years: List[int], config
161-
) -> Dict[str, pd.DataFrame]:
161+
nodes: list[str], techs: list["Code"], t_groups, years: list[int], config
162+
) -> dict[str, pd.DataFrame]:
162163
"""Return constraint data for :attr:`ScenarioFlags.ELE`.
163164
164165
The text reads as follows as of 2023-02-15:
@@ -307,7 +308,7 @@ class MaybeAdaptR11Source(ExoDataSource):
307308
"""
308309

309310
#: Set of measures recognized by a subclass.
310-
measures: Set[str] = set()
311+
measures: set[str] = set()
311312

312313
#: Mapping from :attr:`.measures` entries to file names.
313314
filename: Mapping[str, str] = dict()
@@ -364,7 +365,7 @@ def __call__(self):
364365
def __repr__(self) -> str:
365366
return self._repr
366367

367-
def get_keys(self) -> Tuple[Key, Key]:
368+
def get_keys(self) -> tuple[Key, Key]:
368369
"""Return the target keys for the (1) raw and (2) transformed data."""
369370
k = self.key or Key(
370371
self.name or self.measure.lower(), ("n", "y") + self.extra_dims

message_ix_models/model/transport/demand.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""Demand calculation for MESSAGEix-Transport."""
22

33
import logging
4-
from typing import TYPE_CHECKING, Dict, List
4+
from typing import TYPE_CHECKING
55

66
import genno
77
import numpy as np
@@ -48,8 +48,8 @@
4848

4949

5050
def dummy(
51-
commodities: List, nodes: List[str], y: List[int], config: dict
52-
) -> Dict[str, pd.DataFrame]:
51+
commodities: list, nodes: list[str], y: list[int], config: dict
52+
) -> dict[str, pd.DataFrame]:
5353
"""Dummy demands.
5454
5555
@@ -241,7 +241,7 @@ def pdt_per_capita(c: Computer) -> None:
241241
# Add `y` dimension. Here for the future fixed point we use y=2 * max(y), e.g.
242242
# 4220 for y=2110. The value doesn't matter, we just need to avoid overlap with y
243243
# in the model.
244-
def _future(qty: "AnyQuantity", years: List[int]) -> "AnyQuantity":
244+
def _future(qty: "AnyQuantity", years: list[int]) -> "AnyQuantity":
245245
return qty.expand_dims(y=[years[-1] * 2])
246246

247247
# Same, but adding y0

message_ix_models/model/transport/factor.py

Lines changed: 8 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -11,20 +11,10 @@
1111
import operator
1212
import re
1313
from abc import ABC, abstractmethod
14+
from collections.abc import Callable, Mapping, Sequence
1415
from dataclasses import dataclass, field
1516
from functools import partial
16-
from typing import (
17-
TYPE_CHECKING,
18-
Any,
19-
Callable,
20-
Dict,
21-
List,
22-
Mapping,
23-
Optional,
24-
Sequence,
25-
Tuple,
26-
Union,
27-
)
17+
from typing import TYPE_CHECKING, Any, Optional, Union
2818

2919
import pandas as pd
3020
from genno import Computer, Key, Quantity
@@ -95,7 +85,7 @@ class Constant(Layer):
9585
value: Quantity
9686

9787
#: Dimensions of the result.
98-
dims: Tuple[str, ...]
88+
dims: tuple[str, ...]
9989

10090
operation = operator.mul
10191

@@ -183,12 +173,12 @@ class Map(Layer):
183173
"""
184174

185175
dim: str
186-
values: Dict[str, Layer]
176+
values: dict[str, Layer]
187177

188178
operation = operator.mul
189179

190180
def __init__(
191-
self, dim: str, values: Optional[Dict[str, Layer]] = None, **value_kwargs: Layer
181+
self, dim: str, values: Optional[dict[str, Layer]] = None, **value_kwargs: Layer
192182
):
193183
self.dim = dim
194184
self.values = values or value_kwargs
@@ -215,7 +205,7 @@ class ScenarioSetting(Layer):
215205
"""
216206

217207
#: Mapping from scenario identifier to setting label.
218-
setting: Dict[Any, str]
208+
setting: dict[Any, str]
219209

220210
#: Default setting.
221211
default: str
@@ -310,7 +300,7 @@ class Factor:
310300
"""
311301

312302
#: Ordered list of :class:`.Layer`.
313-
layers: List[Layer] = field(default_factory=list)
303+
layers: list[Layer] = field(default_factory=list)
314304

315305
def __hash__(self):
316306
return hash(tuple(self.layers))
@@ -360,7 +350,7 @@ def add_tasks(
360350
)
361351

362352
def __call__(
363-
self, config, *coords, dims: Tuple[str, ...], scenario_expr: str
353+
self, config, *coords, dims: tuple[str, ...], scenario_expr: str
364354
) -> Quantity:
365355
"""Invoke :meth:`quantify`, for use with :mod:`genno`."""
366356
kw = dict(zip(dims, coords))

0 commit comments

Comments
 (0)