_strutils.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. from __future__ import annotations
  2. from base64 import b64decode, b64encode
  3. from typing import Any
  4. def removeprefix(s: str, prefix: str) -> str:
  5. """Removes a prefix from a string.
  6. This roughly backports the built-in `str.removeprefix` function from Python 3.9+.
  7. Once Python 3.8 support is dropped, just replace this with `str.removeprefix`.
  8. """
  9. return s[len(prefix) :] if s.startswith(prefix) else s
  10. def removesuffix(s: str, suffix: str) -> str:
  11. """Removes a suffix from a string.
  12. This roughly backports the built-in `str.removesuffix` function from Python 3.9+.
  13. Once Python 3.8 support is dropped, just replace this with `str.removesuffix`.
  14. """
  15. return s[: -len(suffix)] if s.endswith(suffix) else s
  16. def ensureprefix(s: str, prefix: str) -> str:
  17. """Ensures the string has the given prefix prepended."""
  18. return s if s.startswith(prefix) else f"{prefix}{s}"
  19. def ensuresuffix(s: str, suffix: str) -> str:
  20. """Ensures the string has the given suffix appended."""
  21. return s if s.endswith(suffix) else f"{s}{suffix}"
  22. def nameof(obj: Any, full: bool = True) -> str:
  23. """Internal convenience helper that returns the object's `__name__` or `__qualname__`.
  24. If `full` is True, attempt to return the object's `__qualname__` attribute,
  25. falling back on the `__name__` attribute.
  26. """
  27. return getattr(obj, "__qualname__", obj.__name__) if full else obj.__name__
  28. def b64decode_ascii(s: str) -> str:
  29. """Returns the decoded base64 string interpreted as ASCII.
  30. Convenience function for directly converting `str -> str`.
  31. """
  32. return b64decode(s).decode("ascii")
  33. def b64encode_ascii(s: str) -> str:
  34. """Returns the base64 encoding of the string's ASCII bytes.
  35. Convenience function for directly converting `str -> str`.
  36. """
  37. return b64encode(s.encode("ascii")).decode("ascii")