Coverage for src/wonka/utilities.py: 100%
35 statements
« prev ^ index » next coverage.py v7.14.1, created at 2026-10-30 22:54 +0000
« prev ^ index » next coverage.py v7.14.1, created at 2026-10-30 22:54 +0000
1"""Private tools used throughout `wonka`.
3Every function in this module is private and documented in its own docstring.
5"""
7from __future__ import annotations
9import inspect
10import pathlib
11import re
12from collections.abc import Iterator
13from typing import Any
15""" Private Functions """
18def _iterify(item: Any) -> Iterator[Any]:
19 """Returns `item` as an iterator, but does not iterate `str` types.
21 Args:
22 item: item to turn into an iterator.
24 Returns:
25 Iterator of `item`. `None` becomes an empty iterator. A `str` or `bytes`
26 type (or any non-iterable) is wrapped so that it is returned as a
27 single item.
29 """
30 if item is None:
31 return iter(())
32 if isinstance(item, str | bytes):
33 return iter([item])
34 try:
35 return iter(item)
36 except TypeError:
37 return iter((item,))
40def _namify(item: Any) -> str:
41 """Returns `str` name representation of `item`.
43 A `str` is returned as is. An instance with a `str` `name` attribute
44 returns that attribute. Otherwise, the snake case name of `item` (if it is
45 a class or function) or of its class (if it is an instance) is returned.
47 Args:
48 item: item to determine a `str` name for.
50 Returns:
51 A name representation of `item`.
53 """
54 if isinstance(item, str):
55 return item
56 if (
57 hasattr(item, 'name')
58 and not inspect.isclass(item)
59 and isinstance(item.name, str)):
60 return item.name
61 try:
62 return _snakify(item.__name__)
63 except AttributeError:
64 return _snakify(item.__class__.__name__)
67def _pathlibify(item: str | pathlib.Path) -> pathlib.Path:
68 """Converts a `str` path to a `pathlib.Path` type.
70 Args:
71 item: item to convert, if it is not already a `pathlib.Path` type.
73 Returns:
74 `item` converted to `pathlib.Path`.
76 Raises:
77 TypeError: if `item` is neither a `str` nor a `pathlib.Path` type.
79 """
80 if isinstance(item, pathlib.Path):
81 return item
82 if isinstance(item, str):
83 return pathlib.Path(item)
84 message = 'item must be a str or pathlib.Path type'
85 raise TypeError(message)
88def _snakify(item: str) -> str:
89 """Converts a capitalized `str` to snake case.
91 Args:
92 item: `str` to convert.
94 Returns:
95 `item` converted to snake case.
97 """
98 item = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', item)
99 return re.sub('([a-z0-9])([A-Z])', r'\1_\2', item).lower()