Make TypeVars private (1) (#68205)

pull/68310/head
Marc Mueller 2022-03-17 18:52:38 +01:00 committed by GitHub
parent a9c383a1e5
commit be7ef6115c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 28 additions and 32 deletions

View File

@ -8,7 +8,7 @@ from homeassistant.core import callback
from .const import REDACTED from .const import REDACTED
T = TypeVar("T") _T = TypeVar("_T")
@overload @overload
@ -17,18 +17,18 @@ def async_redact_data(data: Mapping, to_redact: Iterable[Any]) -> dict: # type:
@overload @overload
def async_redact_data(data: T, to_redact: Iterable[Any]) -> T: def async_redact_data(data: _T, to_redact: Iterable[Any]) -> _T:
... ...
@callback @callback
def async_redact_data(data: T, to_redact: Iterable[Any]) -> T: def async_redact_data(data: _T, to_redact: Iterable[Any]) -> _T:
"""Redact sensitive data in a dict.""" """Redact sensitive data in a dict."""
if not isinstance(data, (Mapping, list)): if not isinstance(data, (Mapping, list)):
return data return data
if isinstance(data, list): if isinstance(data, list):
return cast(T, [async_redact_data(val, to_redact) for val in data]) return cast(_T, [async_redact_data(val, to_redact) for val in data])
redacted = {**data} redacted = {**data}
@ -40,4 +40,4 @@ def async_redact_data(data: T, to_redact: Iterable[Any]) -> T:
elif isinstance(value, list): elif isinstance(value, list):
redacted[key] = [async_redact_data(item, to_redact) for item in value] redacted[key] = [async_redact_data(item, to_redact) for item in value]
return cast(T, redacted) return cast(_T, redacted)

View File

@ -99,15 +99,13 @@ STAGE_3_SHUTDOWN_TIMEOUT = 30
block_async_io.enable() block_async_io.enable()
T = TypeVar("T") _T = TypeVar("_T")
_R = TypeVar("_R") _R = TypeVar("_R")
_R_co = TypeVar("_R_co", covariant=True) # pylint: disable=invalid-name _R_co = TypeVar("_R_co", covariant=True) # pylint: disable=invalid-name
# Internal; not helpers.typing.UNDEFINED due to circular dependency # Internal; not helpers.typing.UNDEFINED due to circular dependency
_UNDEF: dict[Any, Any] = {} _UNDEF: dict[Any, Any] = {}
# pylint: disable=invalid-name _CallableT = TypeVar("_CallableT", bound=Callable[..., Any])
CALLABLE_T = TypeVar("CALLABLE_T", bound=Callable[..., Any]) CALLBACK_TYPE = Callable[[], None] # pylint: disable=invalid-name
CALLBACK_TYPE = Callable[[], None]
# pylint: enable=invalid-name
CORE_STORAGE_KEY = "core.config" CORE_STORAGE_KEY = "core.config"
CORE_STORAGE_VERSION = 1 CORE_STORAGE_VERSION = 1
@ -165,7 +163,7 @@ def valid_state(state: str) -> bool:
return len(state) <= MAX_LENGTH_STATE_STATE return len(state) <= MAX_LENGTH_STATE_STATE
def callback(func: CALLABLE_T) -> CALLABLE_T: def callback(func: _CallableT) -> _CallableT:
"""Annotation to mark method as safe to call from within the event loop.""" """Annotation to mark method as safe to call from within the event loop."""
setattr(func, "_hass_callback", True) setattr(func, "_hass_callback", True)
return func return func
@ -480,8 +478,8 @@ class HomeAssistant:
@callback @callback
def async_add_executor_job( def async_add_executor_job(
self, target: Callable[..., T], *args: Any self, target: Callable[..., _T], *args: Any
) -> asyncio.Future[T]: ) -> asyncio.Future[_T]:
"""Add an executor job from within the event loop.""" """Add an executor job from within the event loop."""
task = self.loop.run_in_executor(None, target, *args) task = self.loop.run_in_executor(None, target, *args)

View File

@ -35,9 +35,7 @@ from .util.async_ import gather_with_concurrency
if TYPE_CHECKING: if TYPE_CHECKING:
from .core import HomeAssistant from .core import HomeAssistant
CALLABLE_T = TypeVar( # pylint: disable=invalid-name _CallableT = TypeVar("_CallableT", bound=Callable[..., Any])
"CALLABLE_T", bound=Callable[..., Any]
)
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -805,7 +803,7 @@ class Helpers:
return wrapped return wrapped
def bind_hass(func: CALLABLE_T) -> CALLABLE_T: def bind_hass(func: _CallableT) -> _CallableT:
"""Decorate function to indicate that first argument is hass.""" """Decorate function to indicate that first argument is hass."""
setattr(func, "__bind_hass", True) setattr(func, "__bind_hass", True)
return func return func

View File

@ -22,7 +22,7 @@ from homeassistant.util import dt as dt_util
# mypy: allow-untyped-calls, allow-untyped-defs, no-check-untyped-defs # mypy: allow-untyped-calls, allow-untyped-defs, no-check-untyped-defs
# mypy: no-warn-return-any # mypy: no-warn-return-any
CALLABLE_T = TypeVar("CALLABLE_T", bound=Callable) # pylint: disable=invalid-name _CallableT = TypeVar("_CallableT", bound=Callable)
BENCHMARKS: dict[str, Callable] = {} BENCHMARKS: dict[str, Callable] = {}
@ -54,7 +54,7 @@ async def run_benchmark(bench):
await hass.async_stop() await hass.async_stop()
def benchmark(func: CALLABLE_T) -> CALLABLE_T: def benchmark(func: _CallableT) -> _CallableT:
"""Decorate to mark a benchmark.""" """Decorate to mark a benchmark."""
BENCHMARKS[func.__name__] = func BENCHMARKS[func.__name__] = func
return func return func

View File

@ -15,8 +15,8 @@ import slugify as unicode_slug
from .dt import as_local, utcnow from .dt import as_local, utcnow
T = TypeVar("T") _T = TypeVar("_T")
U = TypeVar("U") # pylint: disable=invalid-name _U = TypeVar("_U")
RE_SANITIZE_FILENAME = re.compile(r"(~|\.\.|/|\\)") RE_SANITIZE_FILENAME = re.compile(r"(~|\.\.|/|\\)")
RE_SANITIZE_PATH = re.compile(r"(~|\.(\.)+)") RE_SANITIZE_PATH = re.compile(r"(~|\.(\.)+)")
@ -63,8 +63,8 @@ def repr_helper(inp: Any) -> str:
def convert( def convert(
value: T | None, to_type: Callable[[T], U], default: U | None = None value: _T | None, to_type: Callable[[_T], _U], default: _U | None = None
) -> U | None: ) -> _U | None:
"""Convert value to to_type, returns default if fails.""" """Convert value to to_type, returns default if fails."""
try: try:
return default if value is None else to_type(value) return default if value is None else to_type(value)

View File

@ -3,10 +3,10 @@ from __future__ import annotations
from typing import TypeVar from typing import TypeVar
T = TypeVar("T") _T = TypeVar("_T")
def ordered_list_item_to_percentage(ordered_list: list[T], item: T) -> int: def ordered_list_item_to_percentage(ordered_list: list[_T], item: _T) -> int:
"""Determine the percentage of an item in an ordered list. """Determine the percentage of an item in an ordered list.
When using this utility for fan speeds, do not include "off" When using this utility for fan speeds, do not include "off"
@ -29,7 +29,7 @@ def ordered_list_item_to_percentage(ordered_list: list[T], item: T) -> int:
return (list_position * 100) // list_len return (list_position * 100) // list_len
def percentage_to_ordered_list_item(ordered_list: list[T], percentage: int) -> T: def percentage_to_ordered_list_item(ordered_list: list[_T], percentage: int) -> _T:
"""Find the item that most closely matches the percentage in an ordered list. """Find the item that most closely matches the percentage in an ordered list.
When using this utility for fan speeds, do not include "off" When using this utility for fan speeds, do not include "off"

View File

@ -7,11 +7,11 @@ def _readonly(*args: Any, **kwargs: Any) -> Any:
raise RuntimeError("Cannot modify ReadOnlyDict") raise RuntimeError("Cannot modify ReadOnlyDict")
Key = TypeVar("Key") _KT = TypeVar("_KT")
Value = TypeVar("Value") _VT = TypeVar("_VT")
class ReadOnlyDict(dict[Key, Value]): class ReadOnlyDict(dict[_KT, _VT]):
"""Read only version of dict that is compatible with dict types.""" """Read only version of dict that is compatible with dict types."""
__setitem__ = _readonly __setitem__ = _readonly

View File

@ -19,7 +19,7 @@ from .objects import Input, NodeListClass, NodeStrClass
# mypy: allow-untyped-calls, no-warn-return-any # mypy: allow-untyped-calls, no-warn-return-any
JSON_TYPE = Union[list, dict, str] # pylint: disable=invalid-name JSON_TYPE = Union[list, dict, str] # pylint: disable=invalid-name
DICT_T = TypeVar("DICT_T", bound=dict) # pylint: disable=invalid-name _DictT = TypeVar("_DictT", bound=dict)
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -144,8 +144,8 @@ def _add_reference(
@overload @overload
def _add_reference( def _add_reference(
obj: DICT_T, loader: SafeLineLoader, node: yaml.nodes.Node obj: _DictT, loader: SafeLineLoader, node: yaml.nodes.Node
) -> DICT_T: ) -> _DictT:
... ...