jpayne@7: from __future__ import annotations jpayne@7: jpayne@7: import typing jpayne@7: from types import TracebackType jpayne@7: jpayne@7: jpayne@7: def to_bytes( jpayne@7: x: str | bytes, encoding: str | None = None, errors: str | None = None jpayne@7: ) -> bytes: jpayne@7: if isinstance(x, bytes): jpayne@7: return x jpayne@7: elif not isinstance(x, str): jpayne@7: raise TypeError(f"not expecting type {type(x).__name__}") jpayne@7: if encoding or errors: jpayne@7: return x.encode(encoding or "utf-8", errors=errors or "strict") jpayne@7: return x.encode() jpayne@7: jpayne@7: jpayne@7: def to_str( jpayne@7: x: str | bytes, encoding: str | None = None, errors: str | None = None jpayne@7: ) -> str: jpayne@7: if isinstance(x, str): jpayne@7: return x jpayne@7: elif not isinstance(x, bytes): jpayne@7: raise TypeError(f"not expecting type {type(x).__name__}") jpayne@7: if encoding or errors: jpayne@7: return x.decode(encoding or "utf-8", errors=errors or "strict") jpayne@7: return x.decode() jpayne@7: jpayne@7: jpayne@7: def reraise( jpayne@7: tp: type[BaseException] | None, jpayne@7: value: BaseException, jpayne@7: tb: TracebackType | None = None, jpayne@7: ) -> typing.NoReturn: jpayne@7: try: jpayne@7: if value.__traceback__ is not tb: jpayne@7: raise value.with_traceback(tb) jpayne@7: raise value jpayne@7: finally: jpayne@7: value = None # type: ignore[assignment] jpayne@7: tb = None