|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
3 | 3 | from collections.abc import Generator |
4 | | -from typing import TYPE_CHECKING, TypeGuard |
| 4 | +from typing import TYPE_CHECKING, Any, TypeGuard |
| 5 | + |
| 6 | +from htmy.typing import ComponentType |
5 | 7 |
|
6 | 8 | if TYPE_CHECKING: |
7 | | - from .typing import Component, ComponentSequence, ComponentType |
| 9 | + from .typing import Component, ComponentSequence, ComponentType, HTMYComponentType |
8 | 10 |
|
9 | 11 |
|
10 | 12 | def join_components( |
@@ -44,13 +46,26 @@ def join(*items: str | None, separator: str = " ") -> str: |
44 | 46 | return separator.join(i for i in items if i) |
45 | 47 |
|
46 | 48 |
|
| 49 | +def is_htmy_component_type(comp: Any) -> TypeGuard[HTMYComponentType]: |
| 50 | + """Returns whether the given object is a `HTMYComponentType` (has a `htmy` method).""" |
| 51 | + # Lazy check, should be good enough. |
| 52 | + return hasattr(comp, "htmy") |
| 53 | + |
| 54 | + |
| 55 | +def is_component_type(comp: Any) -> TypeGuard[ComponentType]: |
| 56 | + """Returns whether the given object is a `ComponentType`.""" |
| 57 | + # Lazy check when it comes the htmy components, should be good enough. |
| 58 | + # No `is_htmy_component_type()` call to avoid trivial extra function call. |
| 59 | + return comp is None or isinstance(comp, str) or hasattr(comp, "htmy") |
| 60 | + |
| 61 | + |
47 | 62 | def is_component_sequence(comp: Component) -> TypeGuard[ComponentSequence]: |
48 | | - """Returns whether the given component is a component sequence.""" |
| 63 | + """Returns whether the given component is a `ComponentSequence`.""" |
49 | 64 | return isinstance(comp, (list, tuple)) |
50 | 65 |
|
51 | 66 |
|
52 | 67 | def as_component_sequence(comp: Component) -> ComponentSequence: |
53 | | - """Returns the given component as a component sequence.""" |
| 68 | + """Returns the given component as a `ComponentSequence`.""" |
54 | 69 | # mypy doesn't understand the `is_component_sequence` type guard. |
55 | 70 | return comp if is_component_sequence(comp) else (comp,) # type: ignore[return-value] |
56 | 71 |
|
|
0 commit comments