Skip to content

Commit

Permalink
Deprecate and document StatusBase.register
Browse files Browse the repository at this point in the history
  • Loading branch information
james-garner-canonical committed Sep 22, 2024
1 parent 4bb92dd commit 18f09e8
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
30 changes: 27 additions & 3 deletions ops/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -1908,7 +1908,7 @@ def __init__(self, message: str = ''):
self.message = message

def __init_subclass__(cls):
StatusBase.register(cls)
StatusBase._register(cls)

def __eq__(self, other: 'StatusBase') -> bool:
if not isinstance(self, type(other)):
Expand Down Expand Up @@ -1941,14 +1941,38 @@ def from_name(cls, name: str, message: str):

@classmethod
def register(cls, child: Type['StatusBase']):
"""Register a Status for the child's name."""
"""Class decorator to register a subclass for lookup using :meth:`from_name`.
Note: this method is deprecated. Registration is now automatic via __init_subclass.
Also, this decorator obscures the class type when used as a decorator.
Note: this method is intended for internal use only.
It is used to make the valid Juju statuses available by name.
Args:
child: A subclass of StatusBase, with a ``name`` attribute of type ``str``.
Returns:
The decorated class, unmodified.
"""
warnings.warn(
'StatusBase.register should not be called. It is intended'
'for internal use only and is superseded by automatic subclass'
'registration via __init_subclass__',
DeprecationWarning,
stacklevel=2,
)
cls._register(child)
return child

@classmethod
def _register(cls, child: Type['StatusBase']) -> None:
if not (hasattr(child, 'name') and isinstance(child.name, str)):
raise TypeError(
f"Can't register StatusBase subclass {child}: ",
'missing required `name: str` class attribute',
)
cls._statuses[child.name] = child
return child

_priorities = {
'error': 5,
Expand Down
3 changes: 3 additions & 0 deletions test/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -830,6 +830,9 @@ class NoNameStatus(ops.StatusBase): # pyright: ignore[reportUnusedClass]
class NonStringNameStatus(ops.StatusBase): # pyright: ignore[reportUnusedClass]
name = None # pyright: ignore[reportAssignmentType]

with pytest.deprecated_call():
ops.StatusBase.register(ops.ActiveStatus)

def test_status_repr(self):
test_cases = {
"ActiveStatus('Seashell')": ops.ActiveStatus('Seashell'),
Expand Down

0 comments on commit 18f09e8

Please sign in to comment.