|
43 | 43 | # - https://github.com/msgpack/msgpack-python#packingunpacking-of-custom-data-type
|
44 | 44 |
|
45 | 45 | from __future__ import annotations
|
| 46 | +from inspect import isfunction |
46 | 47 | from pkgutil import resolve_name
|
47 | 48 |
|
48 | 49 |
|
49 | 50 | class NamespacePath(str):
|
50 | 51 | '''
|
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. |
55 | 57 |
|
56 | 58 | '''
|
57 |
| - _ref: object = None |
| 59 | + _ref: object | type | None = None |
58 | 60 |
|
59 |
| - def load_ref(self) -> object: |
| 61 | + def load_ref(self) -> object | type: |
60 | 62 | if self._ref is None:
|
61 | 63 | self._ref = resolve_name(self)
|
62 | 64 | return self._ref
|
63 | 65 |
|
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 |
70 | 92 |
|
71 | 93 | @classmethod
|
72 | 94 | def from_ref(
|
73 | 95 | cls,
|
74 |
| - ref, |
| 96 | + ref: type | object, |
75 | 97 |
|
76 | 98 | ) -> 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