summaryrefslogtreecommitdiff
path: root/src/urllib3/util/util.py
blob: 47523f6de2fae2d38a503810b79f329c63fb98ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from types import TracebackType
from typing import NoReturn, Optional, Type, Union


def to_bytes(
    x: Union[str, bytes], encoding: Optional[str] = None, errors: Optional[str] = None
) -> bytes:
    if isinstance(x, bytes):
        return x
    elif not isinstance(x, str):
        raise TypeError(f"not expecting type {type(x).__name__}")
    if encoding or errors:
        return x.encode(encoding or "utf-8", errors=errors or "strict")
    return x.encode()


def to_str(
    x: Union[str, bytes], encoding: Optional[str] = None, errors: Optional[str] = None
) -> str:
    if isinstance(x, str):
        return x
    elif not isinstance(x, bytes):
        raise TypeError(f"not expecting type {type(x).__name__}")
    if encoding or errors:
        return x.decode(encoding or "utf-8", errors=errors or "strict")
    return x.decode()


def reraise(
    tp: Optional[Type[BaseException]],
    value: BaseException,
    tb: Optional[TracebackType] = None,
) -> NoReturn:
    try:
        if value.__traceback__ is not tb:
            raise value.with_traceback(tb)
        raise value
    finally:
        value = None  # type: ignore
        tb = None