_strutils.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. from __future__ import annotations
  2. from base64 import b64decode, b64encode
  3. from typing import Any
  4. def ensureprefix(s: str, prefix: str) -> str:
  5. """Ensures the string has the given prefix prepended."""
  6. return s if s.startswith(prefix) else f"{prefix}{s}"
  7. def ensuresuffix(s: str, suffix: str) -> str:
  8. """Ensures the string has the given suffix appended."""
  9. return s if s.endswith(suffix) else f"{s}{suffix}"
  10. def nameof(obj: Any, full: bool = True) -> str:
  11. """Internal convenience helper that returns the object's `__name__` or `__qualname__`.
  12. If `full` is True, attempt to return the object's `__qualname__` attribute,
  13. falling back on the `__name__` attribute.
  14. """
  15. return getattr(obj, "__qualname__", obj.__name__) if full else obj.__name__
  16. def b64decode_ascii(s: str) -> str:
  17. """Returns the decoded base64 string interpreted as ASCII.
  18. Convenience function for directly converting `str -> str`.
  19. """
  20. return b64decode(s).decode("ascii")
  21. def b64encode_ascii(s: str) -> str:
  22. """Returns the base64 encoding of the string's ASCII bytes.
  23. Convenience function for directly converting `str -> str`.
  24. """
  25. return b64encode(s.encode("ascii")).decode("ascii")