Skip to content

Commit 5154ca2

Browse files
committed
Enforce type annotations on functions
1 parent b6869c1 commit 5154ca2

17 files changed

+94
-73
lines changed

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"
55
[tool.setuptools_scm]
66

77
[tool.mypy]
8-
check_untyped_defs = true
8+
disallow_untyped_defs = true
99

1010
[[tool.mypy.overrides]]
1111
module = [

stagpy/__init__.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,17 @@
2222
import shutil
2323
import signal
2424
import sys
25+
import typing
2526

2627
from pkg_resources import get_distribution, DistributionNotFound
2728
from setuptools_scm import get_version
2829
from loam.manager import ConfigurationManager
2930

3031
from . import config
3132

33+
if typing.TYPE_CHECKING:
34+
from typing import NoReturn, Any
35+
3236

3337
def _env(var: str) -> bool:
3438
"""Return whether var is set to True."""
@@ -40,7 +44,7 @@ def _env(var: str) -> bool:
4044
ISOLATED = _env('STAGPY_ISOLATED')
4145

4246

43-
def sigint_handler(*_):
47+
def sigint_handler(*_: Any) -> NoReturn:
4448
"""Handler of SIGINT signal.
4549
4650
It is set when you use StagPy as a command line tool to handle gracefully
@@ -50,7 +54,7 @@ def sigint_handler(*_):
5054
sys.exit()
5155

5256

53-
def _check_config():
57+
def _check_config() -> None:
5458
"""Create config files as necessary."""
5559
config.CONFIG_DIR.mkdir(parents=True, exist_ok=True)
5660
verfile = config.CONFIG_DIR / '.version'
@@ -67,7 +71,7 @@ def _check_config():
6771
shutil.copy(str(stfile_local), str(stfile_conf))
6872

6973

70-
def load_mplstyle():
74+
def load_mplstyle() -> None:
7175
"""Try to load conf.plot.mplstyle matplotlib style."""
7276
import matplotlib.pyplot as plt
7377
if conf.plot.mplstyle:

stagpy/__main__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from . import DEBUG, sigint_handler
88

99

10-
def main():
10+
def main() -> None:
1111
"""Implement StagPy entry point."""
1212
if not DEBUG:
1313
signal.signal(signal.SIGINT, sigint_handler)

stagpy/_helpers.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from . import conf
1010

1111
if TYPE_CHECKING:
12-
from typing import Optional, Any, List, Callable
12+
from typing import Optional, Any, List, Callable, NoReturn
1313
from matplotlib.figure import Figure
1414
from numpy import ndarray
1515

@@ -52,7 +52,7 @@ def scilabel(value: float, precision: int = 2) -> str:
5252

5353

5454
def saveplot(fig: Figure, *name_args: Any, close: bool = True,
55-
**name_kwargs: Any):
55+
**name_kwargs: Any) -> None:
5656
"""Save matplotlib figure.
5757
5858
You need to provide :data:`stem` as a positional or keyword argument (see
@@ -109,7 +109,7 @@ def list_of_vars(arg_plot: str) -> List[List[List[str]]]:
109109
return [lov for lov in lovs if lov]
110110

111111

112-
def find_in_sorted_arr(value: Any, array: ndarray, after=False) -> int:
112+
def find_in_sorted_arr(value: Any, array: ndarray, after: bool = False) -> int:
113113
"""Return position of element in a sorted array.
114114
115115
Returns:
@@ -150,7 +150,7 @@ def __init__(self, thunk: Callable[[T], V]):
150150
self._cache_name = f'_cropped_{self._name}'
151151
self.__doc__ = thunk.__doc__
152152

153-
def __get__(self, instance: T, _) -> V:
153+
def __get__(self, instance: T, _: Any) -> V:
154154
try:
155155
return getattr(instance, self._cache_name)
156156
except AttributeError:
@@ -159,6 +159,6 @@ def __get__(self, instance: T, _) -> V:
159159
setattr(instance, self._cache_name, cached_value)
160160
return cached_value
161161

162-
def __set__(self, instance: T, _):
162+
def __set__(self, instance: T, _: Any) -> NoReturn:
163163
raise AttributeError(
164164
f'Cannot set {self._name} property of {instance!r}')

stagpy/_step.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919

2020
if typing.TYPE_CHECKING:
2121
from typing import (Dict, Any, Mapping, List, Iterator, Tuple, Optional,
22-
Callable)
22+
Callable, NoReturn)
2323
from numpy import ndarray
2424
from pandas import DataFrame, Series
2525
from .datatypes import Varf
@@ -148,7 +148,7 @@ def p_centers(self) -> ndarray:
148148
y_walls = p_walls
149149
y_centers = p_centers
150150

151-
def _init_shape(self):
151+
def _init_shape(self) -> None:
152152
"""Determine shape of geometry."""
153153
shape = self._step.sdat.par['geometry']['shape'].lower()
154154
aspect = self._header['aspect']
@@ -280,7 +280,7 @@ def _present_fields(self) -> List[str]:
280280
def __iter__(self) -> Iterator[str]:
281281
return iter(self._present_fields)
282282

283-
def __contains__(self, item) -> bool:
283+
def __contains__(self, item: Any) -> bool:
284284
try:
285285
return self[item] is not None
286286
except error.MissingDataError:
@@ -289,7 +289,7 @@ def __contains__(self, item) -> bool:
289289
def __len__(self) -> int:
290290
return len(self._present_fields)
291291

292-
def __eq__(self, other) -> bool:
292+
def __eq__(self, other: object) -> bool:
293293
return self is other
294294

295295
def _get_raw_data(self, name: str) -> Tuple[List[str], Any]:
@@ -327,7 +327,7 @@ def _get_raw_data(self, name: str) -> Tuple[List[str], Any]:
327327
break
328328
return list_fvar, parsed_data
329329

330-
def _set(self, name: str, fld: ndarray):
330+
def _set(self, name: str, fld: ndarray) -> None:
331331
sdat = self.step.sdat
332332
col_fld = sdat._collected_fields
333333
col_fld.append((self.step.istep, name))
@@ -337,7 +337,7 @@ def _set(self, name: str, fld: ndarray):
337337
del sdat.steps[istep].fields[fld_name]
338338
self._data[name] = Field(fld, self._vars[name])
339339

340-
def __delitem__(self, name):
340+
def __delitem__(self, name: str) -> None:
341341
if name in self._data:
342342
del self._data[name]
343343

@@ -404,7 +404,7 @@ def __getitem__(self, name: str) -> Optional[List[ndarray]]:
404404
self._data[name] = None
405405
return self._data[name]
406406

407-
def __iter__(self):
407+
def __iter__(self) -> NoReturn:
408408
raise TypeError('tracers collection is not iterable')
409409

410410

stagpy/args.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ def _sub(cmd: Any, *sections: str) -> Subcmd:
2424
return Subcmd(baredoc(cmd), *sections, func=cmd_func)
2525

2626

27-
def _bare_cmd():
27+
def _bare_cmd() -> None:
2828
"""Print help message when no arguments are given."""
2929
print(doc_module)
3030
print('Run `stagpy -h` for usage')

stagpy/commands.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
from .datatypes import Varf, Varr, Vart
2424

2525

26-
def info_cmd():
26+
def info_cmd() -> None:
2727
"""Print basic information about StagYY run.
2828
2929
Other Parameters:
@@ -74,7 +74,8 @@ def info_cmd():
7474

7575

7676
def _pretty_print(key_val: Sequence[Tuple[str, str]], sep: str = ': ',
77-
min_col_width: int = 39, text_width: Optional[int] = None):
77+
min_col_width: int = 39,
78+
text_width: Optional[int] = None) -> None:
7879
"""Print a iterable of key/values.
7980
8081
Args:
@@ -117,14 +118,14 @@ def _pretty_print(key_val: Sequence[Tuple[str, str]], sep: str = ': ',
117118

118119

119120
def _layout(dict_vars: Mapping[str, Union[Varf, Varr, Vart]],
120-
dict_vars_extra: Mapping[str, Callable]):
121+
dict_vars_extra: Mapping[str, Callable]) -> None:
121122
"""Print nicely [(var, description)] from phyvars."""
122123
desc = [(v, m.description) for v, m in dict_vars.items()]
123124
desc.extend((v, baredoc(m)) for v, m in dict_vars_extra.items())
124125
_pretty_print(desc, min_col_width=26)
125126

126127

127-
def var_cmd():
128+
def var_cmd() -> None:
128129
"""Print a list of available variables.
129130
130131
See :mod:`stagpy.phyvars` where the lists of variables organized by command
@@ -153,7 +154,7 @@ def var_cmd():
153154
print()
154155

155156

156-
def version_cmd():
157+
def version_cmd() -> None:
157158
"""Print StagPy version.
158159
159160
Use :data:`stagpy.__version__` to obtain the version in a script.
@@ -162,7 +163,7 @@ def version_cmd():
162163

163164

164165
def report_parsing_problems(
165-
parsing_out: Tuple[Any, Sequence[Path], Sequence[Path]]):
166+
parsing_out: Tuple[Any, Sequence[Path], Sequence[Path]]) -> None:
166167
"""Output message about potential parsing problems."""
167168
_, empty, faulty = parsing_out
168169
if CONFIG_FILE in empty or CONFIG_FILE in faulty:
@@ -177,7 +178,7 @@ def report_parsing_problems(
177178
sep='\n', end='\n\n', file=sys.stderr)
178179

179180

180-
def config_pp(subs: Iterable[str]):
181+
def config_pp(subs: Iterable[str]) -> None:
181182
"""Pretty print of configuration options.
182183
183184
Args:
@@ -198,7 +199,7 @@ def config_pp(subs: Iterable[str]):
198199
print()
199200

200201

201-
def config_cmd():
202+
def config_cmd() -> None:
202203
"""Configuration handling.
203204
204205
Other Parameters:

stagpy/config.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,9 @@ def _slice_or_int(arg: str) -> Union[slice, int]:
3333
return int(arg)
3434

3535

36-
def _list_of(from_str: Callable[[str], T]) -> Callable[[str], Tuple[T]]:
36+
def _list_of(from_str: Callable[[str], T]) -> Callable[[str], Tuple[T, ...]]:
3737
"""Return fn parsing a str as a comma-separated list of given type."""
38-
def parser(arg):
38+
def parser(arg: str) -> Tuple[T, ...]:
3939
return tuple(from_str(v) for v in map(str.strip, arg.split(',')) if v)
4040
return parser
4141

stagpy/field.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@
1818
from typing import Tuple, Optional, Any, Iterable, Dict
1919
from numpy import ndarray
2020
from matplotlib.axes import Axes
21+
from matplotlib.figure import Figure
22+
from matplotlib.collections import QuadMesh
23+
from matplotlib.colorbar import Colorbar
2124
from .datatypes import Varf
2225
from ._step import Step
2326

@@ -154,7 +157,8 @@ def get_meshes_vec(
154157

155158

156159
def plot_scalar(step: Step, var: str, field: Optional[ndarray] = None,
157-
axis: Optional[Axes] = None, **extra: Any):
160+
axis: Optional[Axes] = None, **extra: Any
161+
) -> Tuple[Figure, Axes, QuadMesh, Colorbar]:
158162
"""Plot scalar field.
159163
160164
Args:
@@ -255,7 +259,7 @@ def plot_scalar(step: Step, var: str, field: Optional[ndarray] = None,
255259
return fig, axis, surf, cbar
256260

257261

258-
def plot_iso(axis: Axes, step: Step, var: str, **extra: Any):
262+
def plot_iso(axis: Axes, step: Step, var: str, **extra: Any) -> None:
259263
"""Plot isocontours of scalar field.
260264
261265
Args:
@@ -280,7 +284,7 @@ def plot_iso(axis: Axes, step: Step, var: str, **extra: Any):
280284
axis.contour(xmesh, ymesh, fld, **extra_opts)
281285

282286

283-
def plot_vec(axis: Axes, step: Step, var: str):
287+
def plot_vec(axis: Axes, step: Step, var: str) -> None:
284288
"""Plot vector field.
285289
286290
Args:
@@ -322,7 +326,7 @@ def _findminmax(
322326
return minmax
323327

324328

325-
def cmd():
329+
def cmd() -> None:
326330
"""Implementation of field subcommand.
327331
328332
Other Parameters:

stagpy/parfile.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -626,7 +626,7 @@
626626
})
627627

628628

629-
def _enrich_with_par(par_nml: Namelist, par_file: Path):
629+
def _enrich_with_par(par_nml: Namelist, par_file: Path) -> None:
630630
"""Enrich a par namelist with the content of a file."""
631631
par_new = f90nml.read(str(par_file))
632632
for section, content in par_new.items():

0 commit comments

Comments
 (0)