Release/v0.5.0 #8
2 changed files with 31 additions and 0 deletions
|
|
@ -1,3 +1,4 @@
|
||||||
|
from .attr import get_attrs, get_or_set_attr
|
||||||
from .frame import frame
|
from .frame import frame
|
||||||
from .inherit import inherit
|
from .inherit import inherit
|
||||||
from .nolock import nolock
|
from .nolock import nolock
|
||||||
|
|
@ -6,6 +7,8 @@ from .throw import throw
|
||||||
from .to_async import to_async
|
from .to_async import to_async
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
|
"get_or_set_attr",
|
||||||
|
"get_attrs",
|
||||||
"frame",
|
"frame",
|
||||||
"inherit",
|
"inherit",
|
||||||
"nolock",
|
"nolock",
|
||||||
|
|
|
||||||
28
src/snakia/utils/attr.py
Normal file
28
src/snakia/utils/attr.py
Normal file
|
|
@ -0,0 +1,28 @@
|
||||||
|
from typing import Any, TypeVar
|
||||||
|
|
||||||
|
T = TypeVar("T")
|
||||||
|
|
||||||
|
|
||||||
|
def get_or_set_attr(obj: Any, name: str, default: T) -> T:
|
||||||
|
if not hasattr(obj, name):
|
||||||
|
setattr(obj, name, default)
|
||||||
|
attr = getattr(obj, name)
|
||||||
|
if not isinstance(attr, type(default)):
|
||||||
|
setattr(obj, name, default)
|
||||||
|
return default
|
||||||
|
return attr
|
||||||
|
|
||||||
|
|
||||||
|
def get_attrs(
|
||||||
|
obj: Any, *, use_dir: bool = False, of_class: bool = False
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
if of_class and not isinstance(obj, type):
|
||||||
|
obj = obj.__class__
|
||||||
|
if not use_dir:
|
||||||
|
if hasattr(obj, "__dict__"):
|
||||||
|
return obj.__dict__ # type: ignore
|
||||||
|
if hasattr(obj, "__slots__"):
|
||||||
|
return {k: getattr(obj, k) for k in obj.__slots__}
|
||||||
|
raise NotImplementedError("Unknown layout")
|
||||||
|
else:
|
||||||
|
return {k: getattr(obj, k) for k in dir(obj)}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue