Skip to content

Commit

Permalink
add alias feature to registry
Browse files Browse the repository at this point in the history
  • Loading branch information
yoelcortes committed Sep 4, 2022
1 parent ada32ca commit 9ccb07f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
4 changes: 4 additions & 0 deletions thermosteam/utils/decorators/registered.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ def _registered(cls, ticket_name, autonumber=True):
cls._take_unregistered_ticket = _take_unregistered_ticket
cls._take_ticket = _take_ticket
cls._register = _register
cls.register_alias = register_alias
cls.ID = ID
cls.__repr__ = __repr__
cls.__str__ = __str__
Expand Down Expand Up @@ -82,6 +83,9 @@ def ID(self):
def ID(self, ID):
self._register(ID)

def register_alias(self, alias):
self.registry.register_alias_safely(alias, self)

def __repr__(self):
return f"<{type(self).__name__}: {self.ID}>"

Expand Down
24 changes: 24 additions & 0 deletions thermosteam/utils/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ def check_valid_ID(ID):
'ID may only contain letters, numbers, and/or underscores; '
'no special characters or spaces'
)

def check_valid_alias(alias):
if not isinstance(alias, str):
raise RuntimeError(f"alias must be a string, not a '{type(alias).__name__}' object")
if not alias[0].isalpha():
raise RuntimeError("alias must start with a letter")

class Registry: # pragma: no cover

Expand Down Expand Up @@ -116,6 +122,24 @@ def register(self, ID, obj):
self._open_registration(ID, obj)
self._close_registration(ID, obj)

def register_alias_safely(self, alias, obj):
"""Register object safely, with checks and due warnings."""
check_valid_alias(alias)
data = self.data
if alias in data:
other = data[alias]
if obj is not other and other not in self.safe_to_replace:
warning = RuntimeWarning(
f"alias {repr(alias)} of {repr(other)} has been replaced in registry with {repr(obj)}"
)
warn(warning, stacklevel=getattr(obj, '_stacklevel', 5) - 1)
self.register_alias(alias, obj)

def register_alias(self, alias, obj):
"""Register object alias without warnings or checks."""
self.data[alias] = obj
for i in self.context_levels: i.append(obj)

def _open_registration(self, ID, obj):
data = self.data
ID_old = getattr(obj, '_ID', None)
Expand Down

0 comments on commit 9ccb07f

Please sign in to comment.