Skip to content
Closed
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
15 changes: 14 additions & 1 deletion petsctools/appctx.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
"""The global storage for user data with arbitrary python types."""


_APPCTX_KEY_PREFIX = "petsctools_appctx_key_"


class AppContextKey(str):
"""A custom key type for AppContext.

Expand All @@ -26,7 +29,7 @@ class AppContextKey(str):

@classmethod
def _generate_key(cls):
return f"petsctools_appctx_key_{next(cls._count)}"
return f"{_APPCTX_KEY_PREFIX}{next(cls._count)}"


class AppContext:
Expand Down Expand Up @@ -214,6 +217,16 @@ def get(
except PetscToolsAppctxException:
return default

def getAll(self) -> dict[str, Any]:
"""Return all entries in the app context."""
from petsc4py import PETSc

return {
key: _global_appctx_data[value]
for key, value in PETSc.Options(self.prefix).getAll().items()
if isinstance(value, str) and value.startswith(_APPCTX_KEY_PREFIX)
}


class AppContextManager:
"""
Expand Down
19 changes: 19 additions & 0 deletions tests/test_appctx.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,22 @@ def test_appctx_key():

prm = appctx1['param']
assert prm is prefix1_param


@pytest.mark.skipnopetsc4py
def test_appctx_get_all():
item1 = object()
item2 = object()

optsmngr = petsctools.OptionsManager(
{
"item1": item1,
"item2": item2,
"other_option": 666,
"another_option": None,
},
options_prefix="myprefix",
)
with optsmngr.inserted_options():
appctx = petsctools.AppContext("myprefix")
assert appctx.getAll() == {"item1": item1, "item2": item2}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should also check that AppContext.getAll does not return these things if called outside of the context manager to make sure we aren't erroneously hanging onto objects longer than we should.

Loading