Better type for force_text using overloads/Literal

- If a str is passed in, it returns a str.
- If strings_only = True and a "protected type" is passed in, returns that type.
- Default if it doesn't match the overloads: return a str
This commit is contained in:
Seth Yastrov
2019-11-13 07:47:45 +01:00
committed by Maxim Kurnikov
parent f5f33b061d
commit 7e794534c0

View File

@@ -1,4 +1,6 @@
from typing import Any, Optional
from typing import Any, Optional, TypeVar, Union, Literal, overload
from decimal import Decimal
import datetime
class DjangoUnicodeDecodeError(UnicodeDecodeError):
obj: bytes = ...
@@ -8,7 +10,18 @@ python_2_unicode_compatible: Any
def smart_text(s: Any, encoding: str = ..., strings_only: bool = ..., errors: str = ...) -> str: ...
def is_protected_type(obj: Any) -> bool: ...
def force_text(s: Any, encoding: str = ..., strings_only: bool = ..., errors: str = ...) -> Optional[str]: ...
_ProtectedType = TypeVar(
"_ProtectedType", Union[None, int, float, Decimal, datetime.datetime, datetime.date, datetime.time]
)
@overload
def force_text(s: str, encoding: str = ..., strings_only: bool = ..., errors: str = ...) -> str: ...
@overload
def force_text(
s: _ProtectedType, encoding: str = ..., strings_only: Literal[True] = ..., errors: str = ...,
) -> _ProtectedType: ...
@overload
def force_text(s: Any, encoding: str = ..., strings_only: bool = ..., errors: str = ...) -> str: ...
def smart_bytes(s: Any, encoding: str = ..., strings_only: bool = ..., errors: str = ...) -> bytes: ...
def force_bytes(s: Any, encoding: str = ..., strings_only: bool = ..., errors: str = ...) -> bytes: ...