Skip to content

Commit bee2c36

Browse files
committed
Make NamespacePath work on object refs
Detect if the input ref is a non-func (like an `object` instance) in which case grab its type name using `type()`. Wrap all the name-getting into a new `_mk_fqpn()` static meth: gets the "fully qualified path name" and returns path and name in tuple; port other methds to use it. Refine and update the docs B)
1 parent b36b3d5 commit bee2c36

File tree

1 file changed

+41
-17
lines changed

1 file changed

+41
-17
lines changed

tractor/msg.py

Lines changed: 41 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -43,38 +43,62 @@
4343
# - https://github.com/msgpack/msgpack-python#packingunpacking-of-custom-data-type
4444

4545
from __future__ import annotations
46+
from inspect import isfunction
4647
from pkgutil import resolve_name
4748

4849

4950
class NamespacePath(str):
5051
'''
51-
A serializeable description of a (function) Python object location
52-
described by the target's module path and namespace key meant as
53-
a message-native "packet" to allows actors to point-and-load objects
54-
by absolute reference.
52+
A serializeable description of a (function) Python object
53+
location described by the target's module path and namespace
54+
key meant as a message-native "packet" to allows actors to
55+
point-and-load objects by an absolute ``str`` (and thus
56+
serializable) reference.
5557
5658
'''
57-
_ref: object = None
59+
_ref: object | type | None = None
5860

59-
def load_ref(self) -> object:
61+
def load_ref(self) -> object | type:
6062
if self._ref is None:
6163
self._ref = resolve_name(self)
6264
return self._ref
6365

64-
def to_tuple(
65-
self,
66-
67-
) -> tuple[str, str]:
68-
ref = self.load_ref()
69-
return ref.__module__, getattr(ref, '__name__', '')
66+
@staticmethod
67+
def _mk_fqnp(ref: type | object) -> tuple[str, str]:
68+
'''
69+
Generate a minial ``str`` pair which describes a python
70+
object's namespace path and object/type name.
71+
72+
In more precise terms something like:
73+
- 'py.namespace.path:object_name',
74+
- eg.'tractor.msg:NamespacePath' will be the ``str`` form
75+
of THIS type XD
76+
77+
'''
78+
if (
79+
isinstance(ref, object)
80+
and not isfunction(ref)
81+
):
82+
name: str = type(ref).__name__
83+
else:
84+
name: str = getattr(ref, '__name__')
85+
86+
# fully qualified namespace path, tuple.
87+
fqnp: tuple[str, str] = (
88+
ref.__module__,
89+
name,
90+
)
91+
return fqnp
7092

7193
@classmethod
7294
def from_ref(
7395
cls,
74-
ref,
96+
ref: type | object,
7597

7698
) -> NamespacePath:
77-
return cls(':'.join(
78-
(ref.__module__,
79-
getattr(ref, '__name__', ''))
80-
))
99+
100+
fqnp: tuple[str, str] = cls._mk_fqnp(ref)
101+
return cls(':'.join(fqnp))
102+
103+
def to_tuple(self) -> tuple[str, str]:
104+
return self._mk_fqnp(self.load_ref())

0 commit comments

Comments
 (0)