utils.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. """General shared utilities."""
  2. import logging
  3. import re
  4. from itertools import tee, zip_longest
  5. from typing import Any, Iterable, Tuple
  6. # Do not update the version manually - it is managed by `bumpversion`.
  7. log = logging.getLogger(__name__)
  8. #: Regular expression for stripping non-alphanumeric characters
  9. NON_ALPHANUMERIC_STRIP_RE = re.compile(r'[\W_]+')
  10. def is_blank(string: str) -> bool:
  11. """Return True iff the string contains only whitespaces."""
  12. return not string.strip()
  13. def pairwise(
  14. iterable: Iterable,
  15. default_value: Any,
  16. ) -> Iterable[Tuple[Any, Any]]:
  17. """Return pairs of items from `iterable`.
  18. pairwise([1, 2, 3], default_value=None) -> (1, 2) (2, 3), (3, None)
  19. """
  20. a, b = tee(iterable)
  21. _ = next(b, default_value)
  22. return zip_longest(a, b, fillvalue=default_value)
  23. def common_prefix_length(a: str, b: str) -> int:
  24. """Return the length of the longest common prefix of a and b.
  25. >>> common_prefix_length('abcd', 'abce')
  26. 3
  27. """
  28. for common, (ca, cb) in enumerate(zip(a, b)):
  29. if ca != cb:
  30. return common
  31. return min(len(a), len(b))
  32. def strip_non_alphanumeric(string: str) -> str:
  33. """Strip string from any non-alphanumeric characters."""
  34. return NON_ALPHANUMERIC_STRIP_RE.sub('', string)