Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions docs/migrating.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,13 @@
flopy4 calls every package's period data `period_data`. flopy3 calls it
`stress_period_data` on some packages, and names others' after the input
file's variable. flopy4 still takes flopy3's names, but warns
(`DeprecationWarning`) and will stop taking them in a future release. Constructors only take the old names: read
and assign `period_data`.
(`DeprecationWarning`) and will stop taking them in a future release.

The old names also work as attributes, with the same warning, but only as
names. `wel.stress_period_data` is `wel.period_data`, a dict of rows by period,
not flopy3's `MFTransientList`, so `.get_data()` and `.set_data()` aren't there.
STO's and OC's old attributes raise `AttributeError`, since their values are
shaped differently: use `period_data`.

| flopy3 | flopy4 | packages |
|---|---|---|
Expand Down
44 changes: 42 additions & 2 deletions flopy4/mf6/legacy.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
"""flopy3's constructor keywords, accepted with a deprecation warning.
"""flopy3's constructor keywords and attributes, with a deprecation warning.

flopy3 names a package's period list after its v1 DFN field (CHD's
`stress_period_data`, LAK's `perioddata`, LKT's `lakeperioddata`, ...), and
spreads STO's and OC's over several keywords whose values are shaped
differently. flopy4 calls each of them `period_data`. A generated class
lists flopy3's names in `legacy_kwargs`, and `LegacyKwargs` translates them
when the class is called, before attrs' `__init__` sees them.

The same names work as attributes, by name only: `wel.stress_period_data` is
`wel.period_data`, not flopy3's `MFTransientList`. A keyword that's converted
has no value of its own to read or assign, so its attribute raises instead.
"""

import warnings
Expand All @@ -27,8 +31,44 @@ class Legacy(NamedTuple):
convert: Callable[..., Any] | None = None


class _LegacyAttribute:
"""A class's attribute for a `legacy_kwargs` keyword."""

def __init__(self, old: str, new: Legacy) -> None:
self.old = old
self.new = new

def _name(self, obj: Any, stacklevel: int) -> str:
cls_name = type(obj).__name__
if self.new.convert is not None:
# an AttributeError, so hasattr() is False
raise AttributeError(
f"{cls_name}.{self.old} is gone: flopy4 keeps it in {self.new.name}, "
"shaped differently. See docs/migrating.md."
)
warnings.warn(
f"{cls_name}.{self.old} is deprecated; use {self.new.name}",
DeprecationWarning,
stacklevel=stacklevel,
)
return self.new.name

def __get__(self, obj: Any, objtype: type | None = None) -> Any:
return self if obj is None else getattr(obj, self._name(obj, stacklevel=3))

def __set__(self, obj: Any, value: Any) -> None:
# one more than __get__, for attrs' generated __setattr__
setattr(obj, self._name(obj, stacklevel=4), value)


class LegacyKwargs(ABCMeta):
"""Translate a class's `legacy_kwargs` when it's called."""
"""Translate a class's `legacy_kwargs` when it's called, and give it an
attribute for each."""

def __init__(cls, name: str, bases: tuple, namespace: dict, **kwargs: Any) -> None:
super().__init__(name, bases, namespace, **kwargs)
for old, new in namespace.get("legacy_kwargs", {}).items():
setattr(cls, old, _LegacyAttribute(old, new))

def __call__(cls, *args: Any, **kwargs: Any) -> Any:
legacy = getattr(cls, "legacy_kwargs", None)
Expand Down
51 changes: 50 additions & 1 deletion test/mf6/test_mf6_legacy.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
"""flopy3's period-data constructor keywords, accepted with a warning."""
"""flopy3's period-data constructor keywords and attributes."""

import inspect
import warnings

import attrs
import flopy
import pytest

Expand Down Expand Up @@ -77,6 +78,54 @@ def test_stress_period_data_and_period_data_conflict():
Wel(stress_period_data={}, period_data={})


@pytest.mark.parametrize(
("cls", "old"),
[(Wel, "stress_period_data"), (Lak, "perioddata")],
)
def test_attribute_reads_and_assigns_period_data(cls, old):
pkg = cls(period_data={})
match = f"{old} is deprecated; use period_data"
with pytest.warns(DeprecationWarning, match=match) as record:
assert getattr(pkg, old) is pkg.period_data
assert record[0].filename == __file__

with pytest.warns(DeprecationWarning, match=match) as record:
setattr(pkg, old, {})
assert record[0].filename == __file__
assert pkg.period_data == {}
assert old not in vars(pkg)


def test_attribute_assignment_is_coerced_like_period_data():
wel = Wel()
with pytest.warns(DeprecationWarning):
wel.stress_period_data = {0: [((0, 0, 0), -1.0)]}
assert wel.period_data[0][0].q == -1.0


@pytest.mark.parametrize(
("cls", "old"),
[
(Sto, "steady_state"),
(Sto, "transient"),
(Oc, "saverecord"),
(Oc, "printrecord"),
],
)
def test_converted_attribute_raises(cls, old):
pkg = cls()
with pytest.raises(AttributeError, match=f"{old} is gone.*period_data"):
getattr(pkg, old)
with pytest.raises(AttributeError, match=f"{old} is gone.*period_data"):
setattr(pkg, old, {})
assert not hasattr(pkg, old)


def test_legacy_names_are_not_fields():
for cls in set(get_fnames().values()):
assert not set(cls.legacy_kwargs) & set(attrs.fields_dict(cls)), cls.dfn_name


def test_warning_points_at_caller():
with pytest.warns(DeprecationWarning) as record:
Lak(perioddata={})
Expand Down
Loading