Object: Add properties name, log_name, log_data
Add some introspection properties to Object, to make it suitable as a lightweight base class for named objects. Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
parent
0d3008d656
commit
efa387a533
1 changed files with 48 additions and 1 deletions
|
|
@ -1,12 +1,59 @@
|
|||
from __future__ import print_function
|
||||
|
||||
import abc
|
||||
|
||||
from typing import Any, Iterable, TypeAlias, override
|
||||
|
||||
from . import log
|
||||
|
||||
class Object(object): # export
|
||||
class Object(abc.ABC):
|
||||
|
||||
LogData: TypeAlias = dict[str, dict[str, Any]]
|
||||
|
||||
@staticmethod
|
||||
def _class_path(proxy: object) -> str:
|
||||
owner: type[Any] = getattr(proxy, "__thisclass__")
|
||||
if not isinstance(owner, type):
|
||||
raise TypeError("Expected a super() proxy")
|
||||
return f"{owner.__module__}.{owner.__qualname__}"
|
||||
|
||||
def __init__(self):
|
||||
self.log_level = log.log_level()
|
||||
|
||||
@override
|
||||
def __repr__(self) -> str:
|
||||
return self.name
|
||||
|
||||
@override
|
||||
def __str__(self) -> str:
|
||||
return self._log_name()
|
||||
|
||||
@abc.abstractmethod
|
||||
def _name_parts(self) -> Iterable[str]:
|
||||
yield self.__class__.__name__
|
||||
|
||||
def _log_data(self, buf: LogData) -> None:
|
||||
buf[self._class_path(super())] = {
|
||||
'name': self.name,
|
||||
}
|
||||
|
||||
@property
|
||||
def log_data(self) -> LogData:
|
||||
ret: Object.LogData = {}
|
||||
self._log_data(ret)
|
||||
return ret
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return ' | '.join(self._name_parts())
|
||||
|
||||
def _log_name(self) -> str:
|
||||
return f'{{{self.name}}}'
|
||||
|
||||
@property
|
||||
def log_name(self) -> str:
|
||||
return self._log_name()
|
||||
|
||||
def log(self, prio, *args):
|
||||
if self.log_level == log.log_level():
|
||||
log.slog(prio, args)
|
||||
|
|
|
|||
Loading…
Reference in a new issue