Skip to content

Commit ed3548d

Browse files
committed
Refactoring function name to unify the string check, isidentifier and iskeyword assert on a single function
1 parent a629e3e commit ed3548d

File tree

4 files changed

+33
-24
lines changed

4 files changed

+33
-24
lines changed

src/parcels/_core/field.py

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@
1818
AllParcelsErrorCodes,
1919
StatusCode,
2020
)
21-
from parcels._core.utils.string import _assert_valid_python_varname
2221
from parcels._core.utils.time import TimeInterval
22+
from parcels._core.utils.string import _assert_str_and_python_varname
2323
from parcels._core.uxgrid import UxGrid
2424
from parcels._core.xgrid import XGrid, _transpose_xfield_data_to_tzyx
2525
from parcels._reprs import default_repr
@@ -102,10 +102,8 @@ def __init__(
102102
raise ValueError(
103103
f"Expected `data` to be a uxarray.UxDataArray or xarray.DataArray object, got {type(data)}."
104104
)
105-
if not isinstance(name, str):
106-
raise ValueError(f"Expected `name` to be a string, got {type(name)}.")
107-
else:
108-
_assert_valid_python_varname(name)
105+
106+
_assert_str_and_python_varname(name)
109107

110108
if not isinstance(grid, (UxGrid, XGrid)):
111109
raise ValueError(f"Expected `grid` to be a parcels UxGrid, or parcels XGrid object, got {type(grid)}.")
@@ -250,10 +248,7 @@ class VectorField:
250248
def __init__(
251249
self, name: str, U: Field, V: Field, W: Field | None = None, vector_interp_method: Callable | None = None
252250
):
253-
if not isinstance(name, str):
254-
raise ValueError(f"Expected `name` to be a string, got {type(name)}.")
255-
else:
256-
_assert_valid_python_varname(name)
251+
_assert_str_and_python_varname(name)
257252

258253
self.name = name
259254
self.U = U

src/parcels/_core/fieldset.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from parcels._core.utils.string import _assert_valid_python_varname
1515
from parcels._core.utils.time import get_datetime_type_calendar
1616
from parcels._core.utils.time import is_compatible as datetime_is_compatible
17+
from parcels._core.utils.string import _assert_str_and_python_varname
1718
from parcels._core.xgrid import _DEFAULT_XGCM_KWARGS, XGrid
1819
from parcels._logger import logger
1920
from parcels._typing import Mesh
@@ -164,10 +165,7 @@ def add_constant(self, name, value):
164165
`Diffusion <../examples/tutorial_diffusion.ipynb>`__
165166
`Periodic boundaries <../examples/tutorial_periodic_boundaries.ipynb>`__
166167
"""
167-
if not isinstance(name, str):
168-
raise ValueError(f"Expected `name` to be a string, got {type(name)}.")
169-
else:
170-
_assert_valid_python_varname(name)
168+
_assert_str_and_python_varname(name)
171169

172170
if name in self.constants:
173171
raise ValueError(f"FieldSet already has a constant with name '{name}'")

src/parcels/_core/particle.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@
88

99
from parcels._compat import _attrgetter_helper
1010
from parcels._core.statuscodes import StatusCode
11-
from parcels._core.utils.string import _assert_valid_python_varname
1211
from parcels._core.utils.time import TimeInterval
12+
from parcels._core.utils.string import _assert_str_and_python_varname
1313
from parcels._reprs import _format_list_items_multiline
1414

1515
__all__ = ["KernelParticle", "Particle", "ParticleClass", "Variable"]
@@ -45,10 +45,7 @@ def __init__(
4545
to_write: bool | Literal["once"] = True,
4646
attrs: dict | None = None,
4747
):
48-
if not isinstance(name, str):
49-
raise ValueError(f"Expected `name` to be a string, got {type(name)}.")
50-
else:
51-
_assert_valid_python_varname(name)
48+
_assert_str_and_python_varname(name)
5249

5350
try:
5451
dtype = np.dtype(dtype)

src/parcels/_core/utils/string.py

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,28 @@
11
from keyword import iskeyword, kwlist
22

3+
# def _assert_valid_python_varname(name):
4+
# try:
5+
# if name.isidentifier():
6+
# if not iskeyword(name):
7+
# return
8+
# raise ValueError(f"Received invalid Python variable name {name!r}: it is a reserved keyword. Avoid using the following names: {', '.join(kwlist)}")
9+
# else:
10+
# raise ValueError(f"Received invalid Python variable name {name!r}: not a valid identifier.")
11+
# except Exception as e:
12+
# raise ValueError(f"Error validating variable name {name!r}: {e}")
13+
314

4-
def _assert_valid_python_varname(name):
5-
if name.isidentifier() and not iskeyword(name):
6-
return
7-
raise ValueError(
8-
f"Received invalid Python variable name {name!r}. Avoid using the following names: {', '.join(kwlist)}"
9-
)
15+
def _assert_str_and_python_varname(name):
16+
if not isinstance(name, str):
17+
raise TypeError(f"Expected a string for variable name, got {type(name).__name__} instead.")
18+
19+
if not name.isidentifier():
20+
raise ValueError(
21+
f"Received invalid Python variable name {name!r}: not a valid identifier. "
22+
f"HINT: avoid using spaces, special characters, and starting with a number."
23+
)
24+
if iskeyword(name):
25+
raise ValueError(
26+
f"Received invalid Python variable name {name!r}: it is a reserved keyword. "
27+
f"HINT: avoid using the following names: {', '.join(kwlist)}"
28+
)

0 commit comments

Comments
 (0)