diff --git a/project_tooling/make_rst_table.py b/project_tooling/make_rst_table.py index b8b1f373e..69f9158c2 100644 --- a/project_tooling/make_rst_table.py +++ b/project_tooling/make_rst_table.py @@ -16,7 +16,7 @@ def make_table(*cols: str) -> str: lines.append( "| " + "| ".join( - (li if li else "") + " " * (longest[n] - len((li if li else "")) + 1) + (li if li else "") + " " * (longest[n] - len(li if li else "") + 1) for n, li in enumerate(ll) ) + "|" diff --git a/pyproject.toml b/pyproject.toml index 211e4fc56..5541ec1b8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,7 +14,7 @@ description = "Configurable, reproducible, and scalable workflows in Python, via readme = "README.md" requires-python = ">=3.9" dependencies = ["hydra-core >= 1.2.0", - "omegaconf >= 2.2.1", + "omegaconf >= 2.2.3", "typing-extensions >= 4.1.0, !=4.6.0", ] license = { text = "MIT" } @@ -158,7 +158,7 @@ commands = pytest tests/ {posargs: -n auto --maxprocesses=4} [testenv:min-deps] description = Runs test suite against minimum supported versions of dependencies. deps = hydra-core==1.2.0 - omegaconf==2.2.1 + omegaconf==2.2.3 typing-extensions==4.1.0 {[testenv]deps} importlib-resources<6.2.0 diff --git a/src/hydra_zen/_compatibility.py b/src/hydra_zen/_compatibility.py index c38398dd7..9b346fd33 100644 --- a/src/hydra_zen/_compatibility.py +++ b/src/hydra_zen/_compatibility.py @@ -5,11 +5,10 @@ from enum import Enum from functools import partial from pathlib import Path, PosixPath, WindowsPath -from typing import FrozenSet, NamedTuple +from typing import Final, NamedTuple import hydra import omegaconf -from typing_extensions import Final NoneType = type(None) @@ -59,7 +58,7 @@ def _get_version(ver_str: str) -> Version: WindowsPath, } ) -ZEN_SUPPORTED_PRIMITIVES: FrozenSet[type] = frozenset( +ZEN_SUPPORTED_PRIMITIVES: frozenset[type] = frozenset( { set, frozenset, diff --git a/src/hydra_zen/_hydra_overloads.py b/src/hydra_zen/_hydra_overloads.py index a2a04f8b9..e7ad38ed3 100644 --- a/src/hydra_zen/_hydra_overloads.py +++ b/src/hydra_zen/_hydra_overloads.py @@ -24,19 +24,7 @@ import pathlib from dataclasses import is_dataclass from functools import partial, wraps -from typing import ( - IO, - Any, - Callable, - Dict, - List, - Tuple, - Type, - TypeVar, - Union, - cast, - overload, -) +from typing import IO, Any, Callable, TypeVar, Union, cast, overload from hydra.utils import instantiate as hydra_instantiate from omegaconf import MISSING, DictConfig, ListConfig, OmegaConf @@ -59,8 +47,8 @@ def _call_target( _target_: F, _partial_: bool, - args: Tuple[Any, ...], - kwargs: Dict[str, Any], + args: tuple[Any, ...], + kwargs: dict[str, Any], full_key: str, *, target_wrapper: Callable[[F], F], @@ -190,9 +178,9 @@ def instantiate( ListConfig, DictConfig, DataClass_, - Type[DataClass_], - Dict[Any, Any], - List[Any], + type[DataClass_], + dict[Any, Any], + list[Any], ], *args: Any, _target_wrapper_: Union[Callable[[F], F], None] = ..., diff --git a/src/hydra_zen/_launch.py b/src/hydra_zen/_launch.py index a401217e7..df1a1e8d1 100644 --- a/src/hydra_zen/_launch.py +++ b/src/hydra_zen/_launch.py @@ -2,18 +2,14 @@ # SPDX-License-Identifier: MIT import warnings from collections import UserList +from collections.abc import Mapping from dataclasses import fields, is_dataclass from typing import ( TYPE_CHECKING, Any, Callable, - Dict, Generic, - List, - Mapping, Optional, - Tuple, - Type, TypeVar, Union, cast, @@ -34,7 +30,7 @@ from hydra_zen.typing._implementations import DataClass_, InstOrType T = TypeVar("T", bound=Any) -HydraPrimitives: TypeAlias = Union[None, int, float, bool, str, Dict[str, str]] +HydraPrimitives: TypeAlias = Union[None, int, float, bool, str, dict[str, str]] if TYPE_CHECKING: # pragma: no cover # branching needed to deal with pyright type-completeness complaints @@ -54,8 +50,6 @@ class hydra_list(TUserList, Generic[T1]): """Signals that a sequence is provided as a single configured value (i.e. it is not to be iterated over during a multirun)""" - pass - T2 = TypeVar("T2", bound=Union[HydraPrimitives, hydra_list[HydraPrimitives]]) @@ -63,8 +57,6 @@ class hydra_list(TUserList, Generic[T1]): class multirun(TUserList, Generic[T2]): """Signals that a sequence is to be iterated over in a multirun""" - pass - def _safe_name(x: Any) -> str: return getattr(x, "__name__", str(x)) @@ -73,7 +65,7 @@ def _safe_name(x: Any) -> str: def value_check( name: str, value: T, - type_: Union[type, Tuple[type, ...]], + type_: Union[type, tuple[type, ...]], ) -> T: """ For internal use only. @@ -108,7 +100,7 @@ def value_check( OverrideDict: TypeAlias = Mapping[str, OverrideValues] -def _process_dict_overrides(overrides: OverrideDict) -> List[str]: +def _process_dict_overrides(overrides: OverrideDict) -> list[str]: """Convert dict overrides to a list of Hydra CLI compatible args""" launch_overrides = [] for k, v in overrides.items(): @@ -128,7 +120,7 @@ def _process_dict_overrides(overrides: OverrideDict) -> List[str]: def _store_config( - cfg: Union[DataClass_, Type[DataClass_], DictConfig, ListConfig, Mapping[Any, Any]], + cfg: Union[DataClass_, type[DataClass_], DictConfig, ListConfig, Mapping[Any, Any]], config_name: str = "hydra_launch", ) -> str: """Stores configuration object in Hydra's ConfigStore. @@ -164,9 +156,9 @@ def _store_config( def launch( config: Union[InstOrType[DataClass_], Mapping[str, Any]], task_function: Callable[[Any], Any], - overrides: Optional[Union[OverrideDict, List[str]]] = ..., + overrides: Optional[Union[OverrideDict, list[str]]] = ..., multirun: Literal[False] = ..., - version_base: Optional[Union[str, Type[_NotSet]]] = ..., + version_base: Optional[Union[str, type[_NotSet]]] = ..., to_dictconfig: bool = ..., config_name: str = ..., job_name: str = ..., @@ -179,9 +171,9 @@ def launch( def launch( config: Union[InstOrType[DataClass_], Mapping[str, Any]], task_function: Callable[[Any], Any], - overrides: Optional[Union[OverrideDict, List[str]]] = ..., + overrides: Optional[Union[OverrideDict, list[str]]] = ..., multirun: Literal[True] = ..., - version_base: Optional[Union[str, Type[_NotSet]]] = ..., + version_base: Optional[Union[str, type[_NotSet]]] = ..., to_dictconfig: bool = ..., config_name: str = ..., job_name: str = ..., @@ -193,9 +185,9 @@ def launch( def launch( config: Union[InstOrType[DataClass_], Mapping[str, Any]], task_function: Callable[[Any], Any], - overrides: Optional[Union[OverrideDict, List[str]]] = None, + overrides: Optional[Union[OverrideDict, list[str]]] = None, multirun: bool = False, - version_base: Optional[Union[str, Type[_NotSet]]] = _NotSet, + version_base: Optional[Union[str, type[_NotSet]]] = _NotSet, to_dictconfig: bool = False, config_name: str = "zen_launch", job_name: str = "zen_launch", diff --git a/src/hydra_zen/_utils/coerce.py b/src/hydra_zen/_utils/coerce.py index 3ae933e69..76e0715ee 100644 --- a/src/hydra_zen/_utils/coerce.py +++ b/src/hydra_zen/_utils/coerce.py @@ -3,12 +3,11 @@ import inspect from collections import deque +from collections.abc import Sequence from functools import wraps from typing import ( Callable, NamedTuple, - Sequence, - Type, TypeVar, Union, cast, @@ -25,7 +24,7 @@ __all__ = ["coerce_sequences"] -def _is_namedtuple_type(x) -> TypeGuard[Type[NamedTuple]]: # pragma: no cover +def _is_namedtuple_type(x) -> TypeGuard[type[NamedTuple]]: # pragma: no cover try: bases = x.__bases__ fields = x._fields diff --git a/src/hydra_zen/structured_configs/_globals.py b/src/hydra_zen/structured_configs/_globals.py index 3fe09aabb..61b261a52 100644 --- a/src/hydra_zen/structured_configs/_globals.py +++ b/src/hydra_zen/structured_configs/_globals.py @@ -1,9 +1,7 @@ # Copyright (c) 2025 Massachusetts Institute of Technology # SPDX-License-Identifier: MIT # pyright: strict -from typing import FrozenSet - -from typing_extensions import Final +from typing import Final from hydra_zen.funcs import zen_processing @@ -24,7 +22,7 @@ ] -HYDRA_FIELD_NAMES: FrozenSet[str] = frozenset(_names) +HYDRA_FIELD_NAMES: frozenset[str] = frozenset(_names) del _names diff --git a/src/hydra_zen/structured_configs/_implementations.py b/src/hydra_zen/structured_configs/_implementations.py index b0e8104da..d4ee7ed96 100644 --- a/src/hydra_zen/structured_configs/_implementations.py +++ b/src/hydra_zen/structured_configs/_implementations.py @@ -6,7 +6,7 @@ import sys import warnings from collections import Counter, defaultdict, deque -from collections.abc import Collection +from collections.abc import Collection, Mapping, Sequence from dataclasses import ( # use this for runtime checks MISSING, Field as _Field, @@ -23,16 +23,14 @@ from itertools import chain from pathlib import Path, PosixPath, WindowsPath from typing import ( + Annotated, Any, Callable, Dict, - FrozenSet, + Final, Generic, List, - Mapping, Optional, - Sequence, - Set, Tuple, Type, TypeVar, @@ -46,9 +44,7 @@ from omegaconf import DictConfig, ListConfig, _utils as _omegaconf_utils from typing_extensions import ( - Annotated, Concatenate, - Final, Literal, ParamSpec, ParamSpecArgs, @@ -64,9 +60,7 @@ from hydra_zen._compatibility import ( HYDRA_SUPPORTED_PRIMITIVE_TYPES, HYDRA_SUPPORTED_PRIMITIVES, - OMEGACONF_VERSION, ZEN_SUPPORTED_PRIMITIVES, - Version, ) from hydra_zen.errors import ( HydraZenDeprecationWarning, @@ -138,10 +132,10 @@ TD = TypeVar("TD", bound=DataClass_) TC = TypeVar("TC", bound=Callable[..., Any]) TP = TypeVar("TP", bound=_HydraPrimitive) -TB = TypeVar("TB", bound=Union[_SupportedViaBuilds, FrozenSet[Any]]) +TB = TypeVar("TB", bound=Union[_SupportedViaBuilds, frozenset[Any]]) Importable = TypeVar("Importable", bound=Callable[..., Any]) -Field_Entry: TypeAlias = Tuple[str, type, Field[Any]] +Field_Entry: TypeAlias = tuple[str, type, Field[Any]] _JUST_CONVERT_SETTINGS = AllConvert(dataclass=True, flat_target=False) @@ -155,7 +149,7 @@ class _ConversionFn(Protocol): def __call__(self, __x: Any, CBuildsFn: "Type[BuildsFn[Any]]") -> Any: ... -ZEN_VALUE_CONVERSION: Dict[type, _ConversionFn] = {} +ZEN_VALUE_CONVERSION: dict[type, _ConversionFn] = {} # signature param-types _POSITIONAL_ONLY: Final = inspect.Parameter.POSITIONAL_ONLY @@ -260,7 +254,7 @@ def hydrated_dataclass( kw_only: bool = False, slots: bool = False, weakref_slot: bool = False, -) -> Callable[[Type[_T]], Type[_T]]: +) -> Callable[[type[_T]], type[_T]]: """A decorator that uses `builds` to create a dataclass with the appropriate Hydra-specific fields for specifying a targeted config [1]_. @@ -502,7 +496,7 @@ def wrapper(decorated_obj: Any) -> Any: and not f.name.startswith("_zen_") } else: - kwargs: Dict[str, Any] = {} + kwargs: dict[str, Any] = {} out = DefaultBuilds.builds( target, @@ -663,7 +657,7 @@ class ZenField: hint: Any = Any default: Union[Any, Field[Any]] = _utils.field(default=NOTHING) - name: Union[str, Type[NOTHING]] = NOTHING + name: Union[str, type[NOTHING]] = NOTHING zen_convert: InitVar[Optional[ZenConvert]] = None _builds_fn: "Union[BuildsFn[Any], Type[BuildsFn[Any]]]" = _utils.field(default_factory=lambda: DefaultBuilds) # type: ignore @@ -835,12 +829,6 @@ def _sanitized_type( nested=nested, ) - if OMEGACONF_VERSION < Version(2, 2, 3): # pragma: no cover - try: - type_ = {list: List, tuple: Tuple, dict: Dict}.get(type_, type_) - except TypeError: - pass - # Warning: mutating `type_` will mutate the signature being inspected # Even calling deepcopy(`type_`) silently fails to prevent this. origin = get_origin(type_) @@ -877,7 +865,7 @@ def _sanitized_type( # isn't Optional[] return Any - args = cast(Tuple[type, type], args) + args = cast(tuple[type, type], args) optional_type, none_type = args if none_type is not NoneType: @@ -892,10 +880,10 @@ def _sanitized_type( if origin is list or origin is List: if args: - return List[ + return list[ cls._sanitized_type(args[0], primitive_only=False, nested=True) ] - return List + return list if origin is dict or origin is Dict: if args: @@ -905,8 +893,8 @@ def _sanitized_type( ValueType = cls._sanitized_type( args[1], primitive_only=False, nested=True ) - return Dict[KeyType, ValueType] - return Dict + return dict[KeyType, ValueType] + return dict if (origin is tuple or origin is Tuple) and not nested: # hydra silently supports tuples of homogeneous types @@ -916,14 +904,14 @@ def _sanitized_type( # # Otherwise we preserve the annotation as accurately as possible if not args: - return Any if OMEGACONF_VERSION < (2, 2, 3) else Tuple + return tuple - args = cast(Tuple[type, ...], args) + args = cast(tuple[type, ...], args) unique_args = set(args) if any(get_origin(tp) is Unpack for tp in unique_args): # E.g. Tuple[*Ts] - return Tuple[Any, ...] + return tuple[Any, ...] has_ellipses = Ellipsis in unique_args @@ -935,9 +923,9 @@ def _sanitized_type( ) if has_ellipses: - return Tuple[_unique_type, ...] + return tuple[_unique_type, ...] else: - return Tuple[(_unique_type,) * len(args)] + return tuple[(_unique_type,) * len(args)] return Any @@ -962,8 +950,6 @@ def _sanitized_type( or is_dataclass(type_) or (isinstance(type_, type) and issubclass(type_, Enum)) ): - if sys.version_info[:2] == (3, 6) and type_ is Dict: # pragma: no cover - type_ = Dict[Any, Any] if wrap_optional and type_ is not Any: # pragma: no cover # normally get_type_hints automatically resolves Optional[...] @@ -1413,8 +1399,8 @@ def _get_sig_obj(cls, target: Any) -> Any: @overload @classmethod def builds( - cls: Type[Self], - __hydra_target: Type[BuildsWithSig[Type[R], P]], + cls: type[Self], + __hydra_target: type[BuildsWithSig[type[R], P]], *, zen_partial: Literal[False, None] = ..., populate_full_signature: Literal[True], @@ -1424,16 +1410,16 @@ def builds( hydra_convert: Optional[Literal["none", "partial", "all", "object"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[()] = ..., + builds_bases: tuple[()] = ..., zen_dataclass: Optional[DataclassOptions] = None, frozen: bool = ..., zen_convert: Optional[ZenConvert] = ..., - ) -> Type[BuildsWithSig[Type[R], P]]: ... + ) -> type[BuildsWithSig[type[R], P]]: ... @overload @classmethod def builds( - cls: Type[Self], + cls: type[Self], __hydra_target: Callable[P, R], *, zen_partial: Literal[False, None] = ..., @@ -1444,18 +1430,18 @@ def builds( hydra_convert: Optional[Literal["none", "partial", "all", "object"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[()] = ..., + builds_bases: tuple[()] = ..., zen_dataclass: Optional[DataclassOptions] = None, frozen: bool = ..., zen_convert: Optional[ZenConvert] = ..., - ) -> Type[BuildsWithSig[Type[R], P]]: ... + ) -> type[BuildsWithSig[type[R], P]]: ... # partial=False, pop-sig=bool @overload @classmethod def builds( - cls: Type[Self], - __hydra_target: Type[AnyBuilds[Importable]], + cls: type[Self], + __hydra_target: type[AnyBuilds[Importable]], *pos_args: T, zen_partial: Literal[False, None] = ..., populate_full_signature: bool = ..., @@ -1465,18 +1451,18 @@ def builds( hydra_convert: Optional[Literal["none", "partial", "all", "object"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[Type[DataClass_], ...] = ..., + builds_bases: tuple[type[DataClass_], ...] = ..., zen_dataclass: Optional[DataclassOptions] = None, frozen: bool = ..., zen_convert: Optional[ZenConvert] = ..., **kwargs_for_target: T, - ) -> Type[Builds[Importable]]: ... + ) -> type[Builds[Importable]]: ... # partial=False, pop-sig=bool @overload @classmethod def builds( - cls: Type[Self], + cls: type[Self], __hydra_target: Importable, *pos_args: T, zen_partial: Literal[False, None] = ..., @@ -1487,19 +1473,19 @@ def builds( hydra_convert: Optional[Literal["none", "partial", "all", "object"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[Type[DataClass_], ...] = ..., + builds_bases: tuple[type[DataClass_], ...] = ..., zen_dataclass: Optional[DataclassOptions] = None, frozen: bool = ..., zen_convert: Optional[ZenConvert] = ..., **kwargs_for_target: T, - ) -> Type[Builds[Importable]]: ... + ) -> type[Builds[Importable]]: ... # partial=True, pop-sig=bool @overload @classmethod def builds( - cls: Type[Self], - __hydra_target: Type[AnyBuilds[Importable]], + cls: type[Self], + __hydra_target: type[AnyBuilds[Importable]], *pos_args: T, zen_partial: Literal[True] = ..., populate_full_signature: bool = ..., @@ -1509,18 +1495,18 @@ def builds( hydra_convert: Optional[Literal["none", "partial", "all", "object"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[Type[DataClass_], ...] = ..., + builds_bases: tuple[type[DataClass_], ...] = ..., zen_dataclass: Optional[DataclassOptions] = None, frozen: bool = ..., zen_convert: Optional[ZenConvert] = ..., **kwargs_for_target: T, - ) -> Type[PartialBuilds[Importable]]: ... + ) -> type[PartialBuilds[Importable]]: ... # partial=True, pop-sig=bool @overload @classmethod def builds( - cls: Type[Self], + cls: type[Self], __hydra_target: Importable, *pos_args: T, zen_partial: Literal[True] = ..., @@ -1531,19 +1517,19 @@ def builds( hydra_convert: Optional[Literal["none", "partial", "all", "object"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[Type[DataClass_], ...] = ..., + builds_bases: tuple[type[DataClass_], ...] = ..., zen_dataclass: Optional[DataclassOptions] = None, frozen: bool = ..., zen_convert: Optional[ZenConvert] = ..., **kwargs_for_target: T, - ) -> Type[PartialBuilds[Importable]]: ... + ) -> type[PartialBuilds[Importable]]: ... # partial=bool, pop-sig=False @overload @classmethod def builds( - cls: Type[Self], - __hydra_target: Type[AnyBuilds[Importable]], + cls: type[Self], + __hydra_target: type[AnyBuilds[Importable]], *pos_args: T, zen_partial: Optional[bool] = ..., populate_full_signature: Literal[False] = ..., @@ -1553,18 +1539,18 @@ def builds( hydra_convert: Optional[Literal["none", "partial", "all", "object"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[Type[DataClass_], ...] = ..., + builds_bases: tuple[type[DataClass_], ...] = ..., zen_dataclass: Optional[DataclassOptions] = None, frozen: bool = ..., zen_convert: Optional[ZenConvert] = ..., **kwargs_for_target: T, - ) -> Union[Type[Builds[Importable]], Type[PartialBuilds[Importable]]]: ... + ) -> Union[type[Builds[Importable]], type[PartialBuilds[Importable]]]: ... # partial=bool, pop-sig=False @overload @classmethod def builds( - cls: Type[Self], + cls: type[Self], __hydra_target: Importable, *pos_args: T, zen_partial: Optional[bool] = ..., @@ -1575,19 +1561,19 @@ def builds( hydra_convert: Optional[Literal["none", "partial", "all", "object"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[Type[DataClass_], ...] = ..., + builds_bases: tuple[type[DataClass_], ...] = ..., zen_dataclass: Optional[DataclassOptions] = None, frozen: bool = ..., zen_convert: Optional[ZenConvert] = ..., **kwargs_for_target: T, - ) -> Union[Type[Builds[Importable]], Type[PartialBuilds[Importable]]]: ... + ) -> Union[type[Builds[Importable]], type[PartialBuilds[Importable]]]: ... # partial=bool, pop-sig=bool @overload @classmethod def builds( - cls: Type[Self], - __hydra_target: Union[Callable[P, R], Type[Builds[Importable]], Importable], + cls: type[Self], + __hydra_target: Union[Callable[P, R], type[Builds[Importable]], Importable], *pos_args: T, zen_partial: Optional[bool], populate_full_signature: bool = ..., @@ -1597,25 +1583,25 @@ def builds( hydra_convert: Optional[Literal["none", "partial", "all", "object"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[Type[DataClass_], ...] = ..., + builds_bases: tuple[type[DataClass_], ...] = ..., zen_dataclass: Optional[DataclassOptions] = None, frozen: bool = ..., zen_convert: Optional[ZenConvert] = ..., **kwargs_for_target: T, ) -> Union[ - Type[Builds[Importable]], - Type[PartialBuilds[Importable]], - Type[BuildsWithSig[Type[R], P]], + type[Builds[Importable]], + type[PartialBuilds[Importable]], + type[BuildsWithSig[type[R], P]], ]: ... @classmethod def builds( - cls: Type[Self], + cls: type[Self], *pos_args: Union[ Importable, Callable[P, R], - Type[AnyBuilds[Importable]], - Type[BuildsWithSig[Type[R], P]], + type[AnyBuilds[Importable]], + type[BuildsWithSig[type[R], P]], Any, ], zen_partial: Optional[bool] = None, @@ -1626,13 +1612,13 @@ def builds( hydra_recursive: Optional[bool] = None, hydra_convert: Optional[Literal["none", "partial", "all", "object"]] = None, hydra_defaults: Optional[DefaultsList] = None, - builds_bases: Union[Tuple[Type[DataClass_], ...], Tuple[()]] = (), + builds_bases: Union[tuple[type[DataClass_], ...], tuple[()]] = (), zen_dataclass: Optional[DataclassOptions] = None, **kwargs_for_target: Any, ) -> Union[ - Type[Builds[Importable]], - Type[PartialBuilds[Importable]], - Type[BuildsWithSig[Type[R], P]], + type[Builds[Importable]], + type[PartialBuilds[Importable]], + type[BuildsWithSig[type[R], P]], ]: """builds(hydra_target, /, *pos_args, zen_partial=None, zen_wrappers=(), zen_meta=None, populate_full_signature=False, zen_exclude=(), hydra_recursive=None, hydra_convert=None, hydra_defaults=None, builds_bases=(), zen_dataclass=None, **kwargs_for_target) @@ -2337,7 +2323,7 @@ def builds(self,target, populate_full_signature=False, **kw): ) # list[tuple[str, type] | tuple[str, type, Any]] - target_field: List[Union[Tuple[str, Any], Tuple[str, Any, Any]]] + target_field: list[Union[tuple[str, Any], tuple[str, Any, Any]]] # zen_partial behavior: # @@ -2447,7 +2433,7 @@ def builds(self,target, populate_full_signature=False, **kw): target_field.append( ( META_FIELD_NAME, - Tuple[str, ...], + tuple[str, ...], _utils.field(default=tuple(zen_meta), init=False), ), ) @@ -2467,7 +2453,7 @@ def builds(self,target, populate_full_signature=False, **kw): ZEN_WRAPPERS_FIELD_NAME, Union[ Union[str, Builds[Any]], - Tuple[Union[str, Builds[Any]], Any], + tuple[Union[str, Builds[Any]], Any], ], _utils.field(default=validated_wrappers[0], init=False), ), @@ -2478,7 +2464,7 @@ def builds(self,target, populate_full_signature=False, **kw): ZEN_WRAPPERS_FIELD_NAME, Union[ Union[str, Builds[Any]], - Tuple[Union[str, Builds[Any]], Any], + tuple[Union[str, Builds[Any]], Any], ], _utils.field(default=validated_wrappers, init=False), ), @@ -2527,7 +2513,7 @@ def builds(self,target, populate_full_signature=False, **kw): base_fields.append( ( DEFAULTS_LIST_FIELD_NAME, - List[Any], + list[Any], _utils.field( default_factory=lambda: list(hydra_defaults), init=False, @@ -2539,7 +2525,7 @@ def builds(self,target, populate_full_signature=False, **kw): base_fields.append( ( POS_ARG_FIELD_NAME, - Tuple[Any, ...], + tuple[Any, ...], _utils.field( default=tuple( cls._make_hydra_compatible( @@ -2568,7 +2554,7 @@ def builds(self,target, populate_full_signature=False, **kw): + f"{target} does not have an inspectable signature. " f"`builds({_utils.safe_name(target)}, populate_full_signature=True)` is not supported" ) - signature_params: Dict[str, inspect.Parameter] = {} + signature_params: dict[str, inspect.Parameter] = {} # We will turn off signature validation for objects that didn't have # a valid signature. This will enable us to do things like `build(dict, a=1)` target_has_valid_signature: bool = False @@ -2662,9 +2648,9 @@ def builds(self,target, populate_full_signature=False, **kw): NameError, # Unresolvable forward reference AttributeError, # Class doesn't have "__new__" or "__init__" ): - type_hints: Dict[str, Any] = {} + type_hints: dict[str, Any] = {} - sig_by_kind: Dict[Any, List[inspect.Parameter]] = { + sig_by_kind: dict[Any, list[inspect.Parameter]] = { _POSITIONAL_ONLY: [], _POSITIONAL_OR_KEYWORD: [], _VAR_POSITIONAL: [], @@ -2677,7 +2663,7 @@ def builds(self,target, populate_full_signature=False, **kw): # these are the names of the only parameters in the signature of `target` that can # be referenced by name - nameable_params_in_sig: Set[str] = { + nameable_params_in_sig: set[str] = { p.name for p in chain( sig_by_kind[_POSITIONAL_OR_KEYWORD], sig_by_kind[_KEYWORD_ONLY] @@ -2699,7 +2685,7 @@ def builds(self,target, populate_full_signature=False, **kw): if _pos_args: break - fields_set_by_bases: Set[str] = { + fields_set_by_bases: set[str] = { _field.name for _base in builds_bases for _field in fields(_base) @@ -2794,7 +2780,7 @@ def builds(self,target, populate_full_signature=False, **kw): # and is resolved to one of the type annotations supported by hydra if possible, # otherwise, is Any # - arg-value: mutable values are automatically specified using default-factory - user_specified_named_params: Dict[str, Tuple[str, type, Any]] = { + user_specified_named_params: dict[str, tuple[str, type, Any]] = { name: (name, type_hints.get(name, Any), value) for name, value in kwargs_for_target.items() if not zen_exclude(name) @@ -2815,10 +2801,10 @@ def builds(self,target, populate_full_signature=False, **kw): # # Parameter ordering should only differ from the target's signature # if the user specified a value for a parameter that had no default - _fields_with_default_values: List[Field_Entry] = [] + _fields_with_default_values: list[Field_Entry] = [] # we need to keep track of what user-specified params we have set - _seen: Set[str] = set() + _seen: set[str] = set() for n, param in enumerate(signature_params.values()): if n in zen_index_exclude or zen_exclude(param.name): @@ -2916,8 +2902,8 @@ def builds(self,target, populate_full_signature=False, **kw): del field_ # sanitize all types and configured values - sanitized_base_fields: List[ - Union[Tuple[str, Any], Tuple[str, Any, Field[Any]]] + sanitized_base_fields: list[ + Union[tuple[str, Any], tuple[str, Any, Field[Any]]] ] = [] for item in base_fields: @@ -2985,7 +2971,7 @@ def builds(self,target, populate_full_signature=False, **kw): ) return cast( - Union[Type[Builds[Importable]], Type[BuildsWithSig[Type[R], P]]], out + Union[type[Builds[Importable]], type[BuildsWithSig[type[R], P]]], out ) @overload @@ -3034,7 +3020,7 @@ def just( hydra_recursive: Optional[bool] = ..., hydra_convert: Optional[Literal["none", "partial", "all", "object"]] = ..., zen_dataclass: Optional[DataclassOptions] = ..., - ) -> Builds[Type[TB]]: ... + ) -> Builds[type[TB]]: ... @overload @classmethod @@ -3046,7 +3032,7 @@ def just( hydra_recursive: Optional[bool] = ..., hydra_convert: Optional[Literal["none", "partial", "all", "object"]] = ..., zen_dataclass: Optional[DataclassOptions] = ..., - ) -> Type[Builds[Type[TD]]]: ... + ) -> type[Builds[type[TD]]]: ... @overload @classmethod @@ -3118,10 +3104,10 @@ def make_config( hydra_convert: Optional[Literal["none", "partial", "all", "object"]] = None, hydra_defaults: Optional[DefaultsList] = None, zen_dataclass: Optional[DataclassOptions] = None, - bases: Tuple[Type[DataClass_], ...] = (), + bases: tuple[type[DataClass_], ...] = (), zen_convert: Optional[ZenConvert] = None, **fields_as_kwargs: Union[T, ZenField], - ) -> Type[DataClass]: + ) -> type[DataClass]: """ Returns a config with user-defined field names and, optionally, associated default values and/or type annotations. @@ -3228,7 +3214,7 @@ def make_config( **{k: _tmp for k in fields_as_kwargs}, ) - normalized_fields: Dict[str, ZenField] = {} + normalized_fields: dict[str, ZenField] = {} for _field in fields_as_args: if isinstance(_field, str): @@ -3254,7 +3240,7 @@ def make_config( normalized_fields[name] = value # fields without defaults must come first - config_fields: List[Union[Tuple[str, type], Tuple[str, type, Any]]] = [ + config_fields: list[Union[tuple[str, type], tuple[str, type, Any]]] = [ (str(f.name), f.hint) for f in normalized_fields.values() if f.default is NOTHING @@ -3307,7 +3293,7 @@ def make_config( config_fields.append( ( DEFAULTS_LIST_FIELD_NAME, - List[Any], + list[Any], _utils.field( default_factory=lambda: list(hydra_defaults), init=False ), @@ -3339,75 +3325,75 @@ def make_config( f"conflicting configs." ) - return cast(Type[DataClass], out) + return cast(type[DataClass], out) # cover zen_exclude=() -> (1, 2, 3) @overload @classmethod def kwargs_of( - cls: Type[Self], + cls: type[Self], __hydra_target: Callable[P, Any], *, zen_dataclass: Optional[DataclassOptions] = ..., - zen_exclude: Tuple[()], - ) -> Type[BuildsWithSig[Type[Dict[str, Any]], P]]: ... + zen_exclude: tuple[()], + ) -> type[BuildsWithSig[type[dict[str, Any]], P]]: ... @overload @classmethod def kwargs_of( - cls: Type[Self], + cls: type[Self], __hydra_target: Callable[Concatenate[Any, P], Any], *, zen_dataclass: Optional[DataclassOptions] = ..., - zen_exclude: Tuple[Literal[0]], - ) -> Type[BuildsWithSig[Type[Dict[str, Any]], P]]: ... + zen_exclude: tuple[Literal[0]], + ) -> type[BuildsWithSig[type[dict[str, Any]], P]]: ... @overload @classmethod def kwargs_of( - cls: Type[Self], + cls: type[Self], __hydra_target: Callable[Concatenate[Any, Any, P], Any], *, zen_dataclass: Optional[DataclassOptions] = ..., - zen_exclude: Tuple[Literal[0], Literal[1]], - ) -> Type[BuildsWithSig[Type[Dict[str, Any]], P]]: ... + zen_exclude: tuple[Literal[0], Literal[1]], + ) -> type[BuildsWithSig[type[dict[str, Any]], P]]: ... @overload @classmethod def kwargs_of( - cls: Type[Self], + cls: type[Self], __hydra_target: Callable[Concatenate[Any, Any, Any, P], Any], *, zen_dataclass: Optional[DataclassOptions] = ..., - zen_exclude: Tuple[Literal[0], Literal[1], Literal[2]], - ) -> Type[BuildsWithSig[Type[Dict[str, Any]], P]]: ... + zen_exclude: tuple[Literal[0], Literal[1], Literal[2]], + ) -> type[BuildsWithSig[type[dict[str, Any]], P]]: ... # no zen-exclude @overload @classmethod def kwargs_of( - cls: Type[Self], + cls: type[Self], __hydra_target: Callable[P, Any], *, zen_dataclass: Optional[DataclassOptions] = ..., zen_exclude: Literal[None] = ..., - ) -> Type[BuildsWithSig[Type[Dict[str, Any]], P]]: ... + ) -> type[BuildsWithSig[type[dict[str, Any]], P]]: ... @overload @classmethod def kwargs_of( - cls: Type[Self], + cls: type[Self], __hydra_target: Callable[P, Any], *, zen_dataclass: Optional[DataclassOptions] = ..., zen_exclude: Union["Collection[Union[str, int]]", Callable[[str], bool]], - ) -> Type[Builds[Type[Dict[str, Any]]]]: ... + ) -> type[Builds[type[dict[str, Any]]]]: ... @overload @classmethod def kwargs_of( - cls: Type[Self], + cls: type[Self], __hydra_target: Callable[P, Any], *, zen_dataclass: Optional[DataclassOptions] = ..., @@ -3415,11 +3401,11 @@ def kwargs_of( None, "Collection[Union[str, int]]", Callable[[str], bool] ] = ..., **kwarg_overrides: T, - ) -> Type[Builds[Type[Dict[str, Any]]]]: ... + ) -> type[Builds[type[dict[str, Any]]]]: ... @classmethod def kwargs_of( - cls: Type[Self], + cls: type[Self], __hydra_target: Union[ Callable[P, Any], Callable[Concatenate[Any, P], Any], @@ -3433,7 +3419,7 @@ def kwargs_of( ] = None, **kwarg_overrides: T, ) -> Union[ - Type[BuildsWithSig[Type[Dict[str, Any]], P]], Type[Builds[Type[Dict[str, Any]]]] + type[BuildsWithSig[type[dict[str, Any]], P]], type[Builds[type[dict[str, Any]]]] ]: """Returns a config whose signature matches that of the provided target. @@ -3512,7 +3498,6 @@ def kwargs_of( class DefaultBuilds(BuildsFn[SupportedPrimitive]): _default_dataclass_options_for_kwargs_of = {} - pass builds: Final = DefaultBuilds.builds @@ -3524,19 +3509,19 @@ class ConfigComplex: real: Any imag: Any _target_: str = field(default=BuildsFn._get_obj_path(complex), init=False) - CBuildsFn: InitVar[Type[BuildsFn[Any]]] + CBuildsFn: InitVar[type[BuildsFn[Any]]] - def __post_init__(self, CBuildsFn: Type[BuildsFn[Any]]) -> None: + def __post_init__(self, CBuildsFn: type[BuildsFn[Any]]) -> None: del CBuildsFn @dataclass(unsafe_hash=True) class ConfigPath: - _args_: Tuple[str] + _args_: tuple[str] _target_: str = field(default=BuildsFn._get_obj_path(Path), init=False) - CBuildsFn: InitVar[Type[BuildsFn[Any]]] + CBuildsFn: InitVar[type[BuildsFn[Any]]] - def __post_init__(self, CBuildsFn: Type[BuildsFn[Any]]) -> None: # pragma: no cover + def __post_init__(self, CBuildsFn: type[BuildsFn[Any]]) -> None: # pragma: no cover del CBuildsFn @@ -3667,7 +3652,7 @@ def mutable_value( x: _T, *, zen_convert: Optional[ZenConvert] = None, - BuildsFunction: Type[BuildsFn[Any]] = BuildsFn[Any], + BuildsFunction: type[BuildsFn[Any]] = BuildsFn[Any], ) -> _T: """Used to set a mutable object as a default value for a field in a dataclass. @@ -3703,10 +3688,10 @@ def mutable_value( def convert_complex( - value: complex, CBuildsFn: Type[BuildsFn[Any]] -) -> Builds[Type[complex]]: + value: complex, CBuildsFn: type[BuildsFn[Any]] +) -> Builds[type[complex]]: return cast( - Builds[Type[complex]], + Builds[type[complex]], ConfigComplex(real=value.real, imag=value.imag, CBuildsFn=CBuildsFn), ) @@ -3716,9 +3701,9 @@ def convert_complex( if Path in ZEN_SUPPORTED_PRIMITIVES: # pragma: no cover - def convert_path(value: Path, CBuildsFn: Type[BuildsFn[Any]]) -> Builds[Type[Path]]: + def convert_path(value: Path, CBuildsFn: type[BuildsFn[Any]]) -> Builds[type[Path]]: return cast( - Builds[Type[Path]], ConfigPath(_args_=(str(value),), CBuildsFn=CBuildsFn) + Builds[type[Path]], ConfigPath(_args_=(str(value),), CBuildsFn=CBuildsFn) ) ZEN_VALUE_CONVERSION[Path] = convert_path @@ -3727,19 +3712,19 @@ def convert_path(value: Path, CBuildsFn: Type[BuildsFn[Any]]) -> Builds[Type[Pat def _unpack_partial( - value: Partial[_T], CBuildsFn: Type[BuildsFn[Any]] -) -> PartialBuilds[Type[_T]]: - target = cast(Type[_T], value.func) + value: Partial[_T], CBuildsFn: type[BuildsFn[Any]] +) -> PartialBuilds[type[_T]]: + target = cast(type[_T], value.func) return CBuildsFn.builds(target, *value.args, **value.keywords, zen_partial=True)() @dataclass(unsafe_hash=True) class ConfigFromTuple: - _args_: Tuple[Any, ...] + _args_: tuple[Any, ...] _target_: str - CBuildsFn: InitVar[Type[BuildsFn[Any]]] + CBuildsFn: InitVar[type[BuildsFn[Any]]] - def __post_init__(self, CBuildsFn: Type[BuildsFn[Any]]) -> None: + def __post_init__(self, CBuildsFn: type[BuildsFn[Any]]) -> None: self._args_ = ( CBuildsFn._make_hydra_compatible( tuple(self._args_), @@ -3754,9 +3739,9 @@ def __post_init__(self, CBuildsFn: Type[BuildsFn[Any]]) -> None: class ConfigFromDict: _args_: Any _target_: str - CBuildsFn: InitVar[Type[BuildsFn[Any]]] + CBuildsFn: InitVar[type[BuildsFn[Any]]] - def __post_init__(self, CBuildsFn: Type[BuildsFn[Any]]) -> None: + def __post_init__(self, CBuildsFn: type[BuildsFn[Any]]) -> None: self._args_ = ( CBuildsFn._make_hydra_compatible( dict(self._args_), @@ -3773,11 +3758,11 @@ class ConfigRange: stop: InitVar[int] step: InitVar[int] _target_: str = field(default=BuildsFn._get_obj_path(range), init=False) - _args_: Tuple[int, ...] = field(default=(), init=False, repr=False) - CBuildsFn: InitVar[Type[BuildsFn[Any]]] + _args_: tuple[int, ...] = field(default=(), init=False, repr=False) + CBuildsFn: InitVar[type[BuildsFn[Any]]] def __post_init__( - self, start: int, stop: int, step: int, CBuildsFn: Type[BuildsFn[Any]] + self, start: int, stop: int, step: int, CBuildsFn: type[BuildsFn[Any]] ) -> None: del CBuildsFn self._args_ = (start, stop, step) @@ -3785,7 +3770,7 @@ def __post_init__( @dataclass(unsafe_hash=True) class ConfigTimeDelta: - CBuildsFn: InitVar[Type[BuildsFn[Any]]] + CBuildsFn: InitVar[type[BuildsFn[Any]]] days: float = 0.0 seconds: float = 0.0 microseconds: float = 0.0 @@ -3795,18 +3780,18 @@ class ConfigTimeDelta: weeks: float = 0.0 _target_: str = field(default=BuildsFn._get_obj_path(timedelta), init=False) - def __post_init__(self, CBuildsFn: Type[BuildsFn[Any]]) -> None: + def __post_init__(self, CBuildsFn: type[BuildsFn[Any]]) -> None: del CBuildsFn @dataclass(unsafe_hash=True) class ConfigFromDefaultDict: - dict_: Dict[Any, Any] + dict_: dict[Any, Any] default_factory: Any = field(init=False) - CBuildsFn: InitVar[Type[BuildsFn[Any]]] + CBuildsFn: InitVar[type[BuildsFn[Any]]] _target_: str = BuildsFn._get_obj_path(as_default_dict) - def __post_init__(self, CBuildsFn: Type[BuildsFn[Any]]) -> None: + def __post_init__(self, CBuildsFn: type[BuildsFn[Any]]) -> None: assert isinstance(self.dict_, defaultdict) self.default_factory = CBuildsFn.just(self.dict_.default_factory) out = CBuildsFn._make_hydra_compatible( diff --git a/src/hydra_zen/structured_configs/_just.py b/src/hydra_zen/structured_configs/_just.py index da0437865..92a5ddeda 100644 --- a/src/hydra_zen/structured_configs/_just.py +++ b/src/hydra_zen/structured_configs/_just.py @@ -1,7 +1,7 @@ # Copyright (c) 2025 Massachusetts Institute of Technology # SPDX-License-Identifier: MIT -from typing import Any, Callable, FrozenSet, Optional, Type, TypeVar, Union, overload +from typing import Any, Callable, Optional, TypeVar, Union, overload from typing_extensions import Literal @@ -17,7 +17,7 @@ TD = TypeVar("TD", bound=DataClass_) TC = TypeVar("TC", bound=Callable[..., Any]) TP = TypeVar("TP", bound=_HydraPrimitive) -TB = TypeVar("TB", bound=Union[_SupportedViaBuilds, FrozenSet[Any]]) +TB = TypeVar("TB", bound=Union[_SupportedViaBuilds, frozenset[Any]]) __all__ = ["just"] @@ -63,7 +63,7 @@ def just( hydra_recursive: Optional[bool] = ..., hydra_convert: Optional[Literal["none", "partial", "all", "object"]] = ..., zen_dataclass: Optional[DataclassOptions] = ..., -) -> Builds[Type[TB]]: ... +) -> Builds[type[TB]]: ... @overload @@ -74,7 +74,7 @@ def just( hydra_recursive: Optional[bool] = ..., hydra_convert: Optional[Literal["none", "partial", "all", "object"]] = ..., zen_dataclass: Optional[DataclassOptions] = ..., -) -> Type[Builds[Type[TD]]]: ... +) -> type[Builds[type[TD]]]: ... @overload diff --git a/src/hydra_zen/structured_configs/_make_config.py b/src/hydra_zen/structured_configs/_make_config.py index a2f9dc571..bde25b41a 100644 --- a/src/hydra_zen/structured_configs/_make_config.py +++ b/src/hydra_zen/structured_configs/_make_config.py @@ -1,6 +1,6 @@ # Copyright (c) 2025 Massachusetts Institute of Technology # SPDX-License-Identifier: MIT -from typing import Optional, Tuple, Type, Union +from typing import Optional, Union from typing_extensions import Literal @@ -32,10 +32,10 @@ def make_config( hydra_convert: Optional[Literal["none", "partial", "all", "object"]] = None, hydra_defaults: Optional[DefaultsList] = None, zen_dataclass: Optional[DataclassOptions] = None, - bases: Tuple[Type[DataClass_], ...] = (), + bases: tuple[type[DataClass_], ...] = (), zen_convert: Optional[ZenConvert] = None, **fields_as_kwargs: Union[SupportedPrimitive, ZenField], -) -> Type[DataClass]: +) -> type[DataClass]: """ Returns a config with user-defined field names and, optionally, associated default values and/or type annotations. diff --git a/src/hydra_zen/structured_configs/_make_custom_builds.py b/src/hydra_zen/structured_configs/_make_custom_builds.py index 1c7096a20..683da30b2 100644 --- a/src/hydra_zen/structured_configs/_make_custom_builds.py +++ b/src/hydra_zen/structured_configs/_make_custom_builds.py @@ -3,14 +3,13 @@ # pyright: strict import inspect import warnings +from collections.abc import Collection, Mapping from functools import wraps from typing import ( TYPE_CHECKING, Any, Callable, - Collection, - Dict, - Mapping, + Final, Optional, TypeVar, Union, @@ -18,7 +17,7 @@ overload, ) -from typing_extensions import Final, Literal +from typing_extensions import Literal from hydra_zen.errors import HydraZenDeprecationWarning from hydra_zen.typing import DataclassOptions, ZenWrappers @@ -32,7 +31,7 @@ _builds_sig = inspect.signature(builds) -__BUILDS_DEFAULTS: Final[Dict[str, Any]] = { +__BUILDS_DEFAULTS: Final[dict[str, Any]] = { name: p.default for name, p in _builds_sig.parameters.items() if p.kind is p.KEYWORD_ONLY @@ -337,7 +336,7 @@ def make_custom_builds_fn( @wraps(fn) def wrapped(*args: Any, **kwargs: Any) -> Any: - merged_kwargs: Dict[str, Any] = {} + merged_kwargs: dict[str, Any] = {} _dataclass: Optional[DataclassOptions] = kwargs.pop("zen_dataclass", None) if _dataclass is None: diff --git a/src/hydra_zen/structured_configs/_type_guards.py b/src/hydra_zen/structured_configs/_type_guards.py index af662c18a..b032be30f 100644 --- a/src/hydra_zen/structured_configs/_type_guards.py +++ b/src/hydra_zen/structured_configs/_type_guards.py @@ -3,7 +3,7 @@ # pyright: strict from dataclasses import MISSING from functools import partial -from typing import TYPE_CHECKING, Any, Protocol, Type, Union +from typing import TYPE_CHECKING, Any, Protocol, Union from typing_extensions import TypeGuard @@ -87,7 +87,7 @@ def is_just(x: Any) -> TypeGuard[Just[Any]]: if TYPE_CHECKING: # pragma: no cover - def is_dataclass(obj: Any) -> TypeGuard[Union[DataClass_, Type[DataClass_]]]: ... + def is_dataclass(obj: Any) -> TypeGuard[Union[DataClass_, type[DataClass_]]]: ... else: from dataclasses import is_dataclass @@ -230,7 +230,7 @@ def is_partial_builds(x: Any) -> TypeGuard[PartialBuilds[Any]]: class HasOrigin(Protocol): - __origin__: Type[Any] + __origin__: type[Any] def is_generic_type(x: Any) -> TypeGuard[HasOrigin]: diff --git a/src/hydra_zen/structured_configs/_utils.py b/src/hydra_zen/structured_configs/_utils.py index 8fda126bf..7624a8366 100644 --- a/src/hydra_zen/structured_configs/_utils.py +++ b/src/hydra_zen/structured_configs/_utils.py @@ -2,29 +2,13 @@ # SPDX-License-Identifier: MIT import inspect import warnings +from collections.abc import Iterable, Mapping, Sequence from dataclasses import MISSING, field as _field, is_dataclass from keyword import iskeyword -from typing import ( - Any, - Callable, - Dict, - FrozenSet, - Iterable, - List, - Mapping, - Optional, - Sequence, - Set, - Tuple, - Type, - TypeVar, - Union, - cast, - overload, -) +from typing import Any, Callable, Final, Optional, TypeVar, Union, cast, overload from omegaconf import II, DictConfig, ListConfig -from typing_extensions import Final, Literal, TypeGuard +from typing_extensions import Literal, TypeGuard from hydra_zen._compatibility import HYDRA_SUPPORTS_OBJECT_CONVERT from hydra_zen.errors import HydraZenValidationError @@ -39,7 +23,7 @@ convert_types, ) -COMMON_MODULES_WITH_OBFUSCATED_IMPORTS: Tuple[str, ...] = ( +COMMON_MODULES_WITH_OBFUSCATED_IMPORTS: tuple[str, ...] = ( "random", "numpy", "numpy.random", @@ -48,8 +32,8 @@ "torch", ) UNKNOWN_NAME: Final[str] = "" -KNOWN_MUTABLE_TYPES: Set[ - Union[Type[List[Any]], Type[Dict[Any, Any]], Type[Set[Any]]] +KNOWN_MUTABLE_TYPES: set[ + Union[type[list[Any]], type[dict[Any, Any]], type[set[Any]]] ] = {list, dict, set} T = TypeVar("T") @@ -274,11 +258,11 @@ def merge_settings( return settings -_DATACLASS_OPTION_KEYS: FrozenSet[str] = ( +_DATACLASS_OPTION_KEYS: frozenset[str] = ( DataclassOptions.__required_keys__ | DataclassOptions.__optional_keys__ ) -_STRICT_DATACLASS_OPTION_KEYS: FrozenSet[str] = ( +_STRICT_DATACLASS_OPTION_KEYS: frozenset[str] = ( StrictDataclassOptions.__required_keys__ | StrictDataclassOptions.__optional_keys__ ) _STRICT_DATACLASS_OPTION_KEYS.copy() diff --git a/src/hydra_zen/typing/_builds_overloads.py b/src/hydra_zen/typing/_builds_overloads.py index 60227b14d..0a368d0c3 100644 --- a/src/hydra_zen/typing/_builds_overloads.py +++ b/src/hydra_zen/typing/_builds_overloads.py @@ -1,21 +1,12 @@ # Copyright (c) 2025 Massachusetts Institute of Technology # SPDX-License-Identifier: MIT +from collections.abc import Mapping + # Stores overloads for `builds` with different default-values for signature # pyright: strict # pragma: no cover -from typing import ( - Any, - Callable, - Generic, - Mapping, - Optional, - Tuple, - Type, - TypeVar, - Union, - overload, -) +from typing import Any, Callable, Generic, Optional, TypeVar, Union, overload from typing_extensions import Literal, ParamSpec @@ -45,7 +36,7 @@ class StdBuilds(Generic[T]): @overload def __call__( self, - __hydra_target: Type[BuildsWithSig[Type[R], P]], + __hydra_target: type[BuildsWithSig[type[R], P]], *, zen_partial: Literal[False, None] = ..., populate_full_signature: Literal[True], @@ -55,11 +46,11 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[()] = ..., + builds_bases: tuple[()] = ..., frozen: bool = ..., zen_dataclass: Optional[DataclassOptions] = ..., zen_convert: Optional[ZenConvert] = ..., - ) -> Type[BuildsWithSig[Type[R], P]]: ... + ) -> type[BuildsWithSig[type[R], P]]: ... # partial=False, pop-sig=True; no *args, **kwargs, nor builds_bases @overload @@ -75,17 +66,17 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[()] = ..., + builds_bases: tuple[()] = ..., frozen: bool = ..., zen_dataclass: Optional[DataclassOptions] = ..., zen_convert: Optional[ZenConvert] = ..., - ) -> Type[BuildsWithSig[Type[R], P]]: ... + ) -> type[BuildsWithSig[type[R], P]]: ... # partial=False, pop-sig=bool @overload def __call__( self, - __hydra_target: Type[AnyBuilds[Importable]], + __hydra_target: type[AnyBuilds[Importable]], *pos_args: T, zen_partial: Literal[False, None] = ..., populate_full_signature: bool = ..., @@ -95,12 +86,12 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[Type[DataClass_], ...] = ..., + builds_bases: tuple[type[DataClass_], ...] = ..., frozen: bool = ..., zen_dataclass: Optional[DataclassOptions] = ..., zen_convert: Optional[ZenConvert] = ..., **kwargs_for_target: T, - ) -> Type[Builds[Importable]]: ... + ) -> type[Builds[Importable]]: ... @overload def __call__( @@ -115,18 +106,18 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[Type[DataClass_], ...] = ..., + builds_bases: tuple[type[DataClass_], ...] = ..., frozen: bool = ..., zen_dataclass: Optional[DataclassOptions] = ..., zen_convert: Optional[ZenConvert] = ..., **kwargs_for_target: T, - ) -> Type[Builds[Importable]]: ... + ) -> type[Builds[Importable]]: ... # partial=True, pop-sig=bool @overload def __call__( self, - __hydra_target: Type[AnyBuilds[Importable]], + __hydra_target: type[AnyBuilds[Importable]], *pos_args: T, zen_partial: Literal[True] = ..., populate_full_signature: bool = ..., @@ -136,12 +127,12 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[Type[DataClass_], ...] = ..., + builds_bases: tuple[type[DataClass_], ...] = ..., frozen: bool = ..., zen_dataclass: Optional[DataclassOptions] = ..., zen_convert: Optional[ZenConvert] = ..., **kwargs_for_target: T, - ) -> Type[PartialBuilds[Importable]]: ... + ) -> type[PartialBuilds[Importable]]: ... @overload def __call__( @@ -156,18 +147,18 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[Type[DataClass_], ...] = ..., + builds_bases: tuple[type[DataClass_], ...] = ..., frozen: bool = ..., zen_dataclass: Optional[DataclassOptions] = ..., zen_convert: Optional[ZenConvert] = ..., **kwargs_for_target: T, - ) -> Type[PartialBuilds[Importable]]: ... + ) -> type[PartialBuilds[Importable]]: ... # partial=bool, pop-sig=False @overload def __call__( self, - __hydra_target: Type[AnyBuilds[Importable]], + __hydra_target: type[AnyBuilds[Importable]], *pos_args: T, zen_partial: Optional[bool] = ..., populate_full_signature: Literal[False] = ..., @@ -177,14 +168,14 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[Type[DataClass_], ...] = ..., + builds_bases: tuple[type[DataClass_], ...] = ..., frozen: bool = ..., zen_dataclass: Optional[DataclassOptions] = ..., zen_convert: Optional[ZenConvert] = ..., **kwargs_for_target: T, ) -> Union[ - Type[Builds[Importable]], - Type[PartialBuilds[Importable]], + type[Builds[Importable]], + type[PartialBuilds[Importable]], ]: ... @overload @@ -200,21 +191,21 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[Type[DataClass_], ...] = ..., + builds_bases: tuple[type[DataClass_], ...] = ..., frozen: bool = ..., zen_dataclass: Optional[DataclassOptions] = ..., zen_convert: Optional[ZenConvert] = ..., **kwargs_for_target: T, ) -> Union[ - Type[Builds[Importable]], - Type[PartialBuilds[Importable]], + type[Builds[Importable]], + type[PartialBuilds[Importable]], ]: ... # partial=bool, pop-sig=bool @overload def __call__( self, - __hydra_target: Union[Callable[P, R], Type[AnyBuilds[Importable]], Importable], + __hydra_target: Union[Callable[P, R], type[AnyBuilds[Importable]], Importable], *pos_args: T, zen_partial: Optional[bool], populate_full_signature: bool = ..., @@ -224,24 +215,24 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[Type[DataClass_], ...] = ..., + builds_bases: tuple[type[DataClass_], ...] = ..., frozen: bool = ..., zen_dataclass: Optional[DataclassOptions] = ..., zen_convert: Optional[ZenConvert] = ..., **kwargs_for_target: T, ) -> Union[ - Type[Builds[Importable]], - Type[PartialBuilds[Importable]], - Type[BuildsWithSig[Type[R], P]], + type[Builds[Importable]], + type[PartialBuilds[Importable]], + type[BuildsWithSig[type[R], P]], ]: ... def __call__( self, __hydra_target: Union[ Callable[P, R], - Type[Builds[Importable]], + type[Builds[Importable]], Importable, - Type[BuildsWithSig[Type[R], P]], + type[BuildsWithSig[type[R], P]], ], *pos_args: T, zen_partial: Optional[bool] = None, @@ -252,15 +243,15 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = None, hydra_defaults: Optional[DefaultsList] = None, frozen: bool = False, - builds_bases: Union[Tuple[Type[DataClass_], ...], Tuple[()]] = (), + builds_bases: Union[tuple[type[DataClass_], ...], tuple[()]] = (), dataclass_name: Optional[str] = None, zen_dataclass: Optional[DataclassOptions] = None, zen_convert: Optional[ZenConvert] = None, **kwargs_for_target: T, ) -> Union[ - Type[Builds[Importable]], - Type[PartialBuilds[Importable]], - Type[BuildsWithSig[Type[R], P]], + type[Builds[Importable]], + type[PartialBuilds[Importable]], + type[BuildsWithSig[type[R], P]], ]: # pragma: no cover ... @@ -273,7 +264,7 @@ class FullBuilds(Generic[T]): @overload def __call__( self, - __hydra_target: Type[BuildsWithSig[Type[R], P]], + __hydra_target: type[BuildsWithSig[type[R], P]], *, zen_partial: Literal[False, None] = ..., populate_full_signature: Literal[True] = ..., @@ -283,16 +274,16 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[()] = ..., + builds_bases: tuple[()] = ..., frozen: bool = ..., zen_dataclass: Optional[DataclassOptions] = ..., zen_convert: Optional[ZenConvert] = ..., - ) -> Type[BuildsWithSig[Type[R], P]]: ... + ) -> type[BuildsWithSig[type[R], P]]: ... @overload def __call__( self, - __hydra_target: Type[AnyBuilds[Importable]], + __hydra_target: type[AnyBuilds[Importable]], *, zen_partial: Literal[False, None] = ..., populate_full_signature: Literal[True] = ..., @@ -302,11 +293,11 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[()] = ..., + builds_bases: tuple[()] = ..., frozen: bool = ..., zen_dataclass: Optional[DataclassOptions] = ..., zen_convert: Optional[ZenConvert] = ..., - ) -> Type[Builds[Importable]]: ... + ) -> type[Builds[Importable]]: ... @overload def __call__( @@ -321,16 +312,16 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[()] = ..., + builds_bases: tuple[()] = ..., frozen: bool = ..., zen_dataclass: Optional[DataclassOptions] = ..., zen_convert: Optional[ZenConvert] = ..., - ) -> Type[BuildsWithSig[Type[R], P]]: ... + ) -> type[BuildsWithSig[type[R], P]]: ... @overload def __call__( self, - __hydra_target: Type[Union[AnyBuilds[Importable], PartialBuilds[Importable]]], + __hydra_target: type[Union[AnyBuilds[Importable], PartialBuilds[Importable]]], *pos_args: T, zen_partial: Literal[False, None] = ..., populate_full_signature: bool = ..., @@ -340,12 +331,12 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[Type[DataClass_], ...] = ..., + builds_bases: tuple[type[DataClass_], ...] = ..., frozen: bool = ..., zen_dataclass: Optional[DataclassOptions] = ..., zen_convert: Optional[ZenConvert] = ..., **kwargs_for_target: T, - ) -> Type[Builds[Importable]]: ... + ) -> type[Builds[Importable]]: ... @overload def __call__( @@ -360,18 +351,18 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[Type[DataClass_], ...] = ..., + builds_bases: tuple[type[DataClass_], ...] = ..., frozen: bool = ..., zen_dataclass: Optional[DataclassOptions] = ..., zen_convert: Optional[ZenConvert] = ..., **kwargs_for_target: T, - ) -> Type[Builds[Importable]]: ... + ) -> type[Builds[Importable]]: ... # partial=True, pop-sig=bool @overload def __call__( self, - __hydra_target: Type[AnyBuilds[Importable]], + __hydra_target: type[AnyBuilds[Importable]], *pos_args: T, zen_partial: Literal[True] = ..., populate_full_signature: bool = ..., @@ -381,12 +372,12 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[Type[DataClass_], ...] = ..., + builds_bases: tuple[type[DataClass_], ...] = ..., frozen: bool = ..., zen_dataclass: Optional[DataclassOptions] = ..., zen_convert: Optional[ZenConvert] = ..., **kwargs_for_target: T, - ) -> Type[PartialBuilds[Importable]]: ... + ) -> type[PartialBuilds[Importable]]: ... @overload def __call__( @@ -401,18 +392,18 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[Type[DataClass_], ...] = ..., + builds_bases: tuple[type[DataClass_], ...] = ..., frozen: bool = ..., zen_dataclass: Optional[DataclassOptions] = ..., zen_convert: Optional[ZenConvert] = ..., **kwargs_for_target: T, - ) -> Type[PartialBuilds[Importable]]: ... + ) -> type[PartialBuilds[Importable]]: ... # partial=bool, pop-sig=False @overload def __call__( self, - __hydra_target: Type[AnyBuilds[Importable]], + __hydra_target: type[AnyBuilds[Importable]], *pos_args: T, zen_partial: Optional[bool] = ..., populate_full_signature: Literal[False], @@ -422,12 +413,12 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., frozen: bool = ..., - builds_bases: Tuple[Type[DataClass_], ...] = ..., + builds_bases: tuple[type[DataClass_], ...] = ..., dataclass_name: Optional[str] = ..., zen_dataclass: Optional[DataclassOptions] = ..., zen_convert: Optional[ZenConvert] = ..., **kwargs_for_target: T, - ) -> Union[Type[Builds[Importable]], Type[PartialBuilds[Importable]]]: ... + ) -> Union[type[Builds[Importable]], type[PartialBuilds[Importable]]]: ... @overload def __call__( @@ -442,18 +433,18 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., frozen: bool = ..., - builds_bases: Tuple[Type[DataClass_], ...] = ..., + builds_bases: tuple[type[DataClass_], ...] = ..., dataclass_name: Optional[str] = ..., zen_dataclass: Optional[DataclassOptions] = ..., zen_convert: Optional[ZenConvert] = ..., **kwargs_for_target: T, - ) -> Union[Type[Builds[Importable]], Type[PartialBuilds[Importable]]]: ... + ) -> Union[type[Builds[Importable]], type[PartialBuilds[Importable]]]: ... # partial=bool, pop-sig=bool @overload def __call__( self, - __hydra_target: Union[Callable[P, R], Type[AnyBuilds[Importable]], Importable], + __hydra_target: Union[Callable[P, R], type[AnyBuilds[Importable]], Importable], *pos_args: T, zen_partial: Optional[bool], populate_full_signature: bool = ..., @@ -463,15 +454,15 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., frozen: bool = ..., - builds_bases: Tuple[Type[DataClass_], ...] = ..., + builds_bases: tuple[type[DataClass_], ...] = ..., dataclass_name: Optional[str] = ..., zen_dataclass: Optional[DataclassOptions] = ..., zen_convert: Optional[ZenConvert] = ..., **kwargs_for_target: T, ) -> Union[ - Type[Builds[Importable]], - Type[PartialBuilds[Importable]], - Type[BuildsWithSig[Type[R], P]], + type[Builds[Importable]], + type[PartialBuilds[Importable]], + type[BuildsWithSig[type[R], P]], ]: ... def __call__( @@ -479,9 +470,9 @@ def __call__( __hydra_target: Union[ Callable[P, R], Importable, - Type[Builds[Importable]], - Type[PartialBuilds[Importable]], - Type[BuildsWithSig[Type[R], P]], + type[Builds[Importable]], + type[PartialBuilds[Importable]], + type[BuildsWithSig[type[R], P]], ], *pos_args: T, zen_partial: Optional[bool] = None, @@ -492,15 +483,15 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = None, hydra_defaults: Optional[DefaultsList] = None, frozen: bool = False, - builds_bases: Union[Tuple[Type[DataClass_], ...], Tuple[()]] = (), + builds_bases: Union[tuple[type[DataClass_], ...], tuple[()]] = (), dataclass_name: Optional[str] = None, zen_dataclass: Optional[DataclassOptions] = None, zen_convert: Optional[ZenConvert] = None, **kwargs_for_target: T, ) -> Union[ - Type[Builds[Importable]], - Type[PartialBuilds[Importable]], - Type[BuildsWithSig[Type[R], P]], + type[Builds[Importable]], + type[PartialBuilds[Importable]], + type[BuildsWithSig[type[R], P]], ]: # pragma: no cover ... @@ -512,7 +503,7 @@ class PBuilds(Generic[T]): @overload def __call__( self, - __hydra_target: Type[AnyBuilds[Importable]], + __hydra_target: type[AnyBuilds[Importable]], *pos_args: T, zen_partial: Literal[True] = ..., populate_full_signature: bool = ..., @@ -522,12 +513,12 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[Type[DataClass_], ...] = ..., + builds_bases: tuple[type[DataClass_], ...] = ..., frozen: bool = ..., zen_dataclass: Optional[DataclassOptions] = ..., zen_convert: Optional[ZenConvert] = ..., **kwargs_for_target: T, - ) -> Type[PartialBuilds[Importable]]: ... + ) -> type[PartialBuilds[Importable]]: ... @overload def __call__( @@ -542,18 +533,18 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[Type[DataClass_], ...] = ..., + builds_bases: tuple[type[DataClass_], ...] = ..., frozen: bool = ..., zen_dataclass: Optional[DataclassOptions] = ..., zen_convert: Optional[ZenConvert] = ..., **kwargs_for_target: T, - ) -> Type[PartialBuilds[Importable]]: ... + ) -> type[PartialBuilds[Importable]]: ... # partial=False, pop-sig=True; no *args, **kwargs, nor builds_bases @overload def __call__( self, - __hydra_target: Type[BuildsWithSig[Type[R], P]], + __hydra_target: type[BuildsWithSig[type[R], P]], *, zen_partial: Literal[False, None], populate_full_signature: Literal[True], @@ -563,11 +554,11 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[()] = ..., + builds_bases: tuple[()] = ..., frozen: bool = ..., zen_dataclass: Optional[DataclassOptions] = ..., zen_convert: Optional[ZenConvert] = ..., - ) -> Type[BuildsWithSig[Type[R], P]]: ... + ) -> type[BuildsWithSig[type[R], P]]: ... @overload def __call__( @@ -582,17 +573,17 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[()] = ..., + builds_bases: tuple[()] = ..., frozen: bool = ..., zen_dataclass: Optional[DataclassOptions] = ..., zen_convert: Optional[ZenConvert] = ..., - ) -> Type[BuildsWithSig[Type[R], P]]: ... + ) -> type[BuildsWithSig[type[R], P]]: ... # partial=bool, pop-sig=False @overload def __call__( self, - __hydra_target: Type[AnyBuilds[Importable]], + __hydra_target: type[AnyBuilds[Importable]], *pos_args: T, zen_partial: Optional[bool] = ..., populate_full_signature: Literal[False] = ..., @@ -602,14 +593,14 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[Type[DataClass_], ...] = ..., + builds_bases: tuple[type[DataClass_], ...] = ..., frozen: bool = ..., zen_dataclass: Optional[DataclassOptions] = ..., zen_convert: Optional[ZenConvert] = ..., **kwargs_for_target: T, ) -> Union[ - Type[Builds[Importable]], - Type[PartialBuilds[Importable]], + type[Builds[Importable]], + type[PartialBuilds[Importable]], ]: ... @overload @@ -625,14 +616,14 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[Type[DataClass_], ...] = ..., + builds_bases: tuple[type[DataClass_], ...] = ..., frozen: bool = ..., zen_dataclass: Optional[DataclassOptions] = ..., zen_convert: Optional[ZenConvert] = ..., **kwargs_for_target: T, ) -> Union[ - Type[Builds[Importable]], - Type[PartialBuilds[Importable]], + type[Builds[Importable]], + type[PartialBuilds[Importable]], ]: ... # partial=bool, pop-sig=bool @@ -649,24 +640,24 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = ..., hydra_defaults: Optional[DefaultsList] = ..., dataclass_name: Optional[str] = ..., - builds_bases: Tuple[Type[DataClass_], ...] = ..., + builds_bases: tuple[type[DataClass_], ...] = ..., frozen: bool = ..., zen_dataclass: Optional[DataclassOptions] = ..., zen_convert: Optional[ZenConvert] = ..., **kwargs_for_target: T, ) -> Union[ - Type[Builds[Importable]], - Type[PartialBuilds[Importable]], - Type[BuildsWithSig[Type[R], P]], + type[Builds[Importable]], + type[PartialBuilds[Importable]], + type[BuildsWithSig[type[R], P]], ]: ... def __call__( self, __hydra_target: Union[ Callable[P, R], - Type[AnyBuilds[Importable]], + type[AnyBuilds[Importable]], Importable, - Type[BuildsWithSig[Type[R], P]], + type[BuildsWithSig[type[R], P]], ], *pos_args: T, zen_partial: Optional[bool] = True, @@ -677,14 +668,14 @@ def __call__( hydra_convert: Optional[Literal["none", "partial", "all"]] = None, hydra_defaults: Optional[DefaultsList] = None, frozen: bool = False, - builds_bases: Union[Tuple[Type[DataClass_], ...], Tuple[()]] = (), + builds_bases: Union[tuple[type[DataClass_], ...], tuple[()]] = (), dataclass_name: Optional[str] = None, zen_dataclass: Optional[DataclassOptions] = None, zen_convert: Optional[ZenConvert] = None, **kwargs_for_target: T, ) -> Union[ - Type[Builds[Importable]], - Type[PartialBuilds[Importable]], - Type[BuildsWithSig[Type[R], P]], + type[Builds[Importable]], + type[PartialBuilds[Importable]], + type[BuildsWithSig[type[R], P]], ]: # pragma: no cover ... diff --git a/src/hydra_zen/typing/_implementations.py b/src/hydra_zen/typing/_implementations.py index d20700831..5f04d967b 100644 --- a/src/hydra_zen/typing/_implementations.py +++ b/src/hydra_zen/typing/_implementations.py @@ -5,6 +5,7 @@ import sys import types +from collections.abc import ByteString, Mapping, Sequence from dataclasses import _MISSING_TYPE # pyright: ignore[reportPrivateUsage] from datetime import timedelta from enum import Enum @@ -12,26 +13,17 @@ from typing import ( TYPE_CHECKING, Any, - ByteString, Callable, ClassVar, - Dict, - FrozenSet, - List, - Mapping, + Final, NewType, Optional, - Sequence, - Set, - Tuple, - Type, TypeVar, Union, ) from omegaconf import DictConfig, ListConfig from typing_extensions import ( - Final, Literal, ParamSpec, Protocol, @@ -70,7 +62,7 @@ class EmptyDict(TypedDict): T4 = TypeVar("T4", bound=Callable[..., Any]) -InstOrType: TypeAlias = Union[T, Type[T]] +InstOrType: TypeAlias = Union[T, type[T]] if TYPE_CHECKING: @@ -79,7 +71,7 @@ class EmptyDict(TypedDict): class Field(Protocol[T2]): name: str - type: Type[T2] + type: type[T2] default: T2 default_factory: Callable[[], T2] repr: bool @@ -99,13 +91,13 @@ class Partial(Protocol[T2]): def func(self) -> Callable[..., T2]: ... @property - def args(self) -> Tuple[Any, ...]: ... + def args(self) -> tuple[Any, ...]: ... @property - def keywords(self) -> Dict[str, Any]: ... + def keywords(self) -> dict[str, Any]: ... def __new__( - cls: Type[Self], __func: Callable[..., T2], *args: Any, **kwargs: Any + cls: type[Self], __func: Callable[..., T2], *args: Any, **kwargs: Any ) -> Self: ... if TYPE_CHECKING and sys.version_info >= (3, 9): # pragma: no cover @@ -118,7 +110,7 @@ def __class_getitem__(cls, item: Any) -> types.GenericAlias: ... class DataClass_(Protocol): # doesn't provide __init__, __getattribute__, etc. - __dataclass_fields__: ClassVar[Dict[str, Field[Any]]] + __dataclass_fields__: ClassVar[dict[str, Field[Any]]] class DataClass(DataClass_, Protocol): @@ -189,14 +181,14 @@ class HydraPartialBuilds(Builds[T], HydraPartialMixin[T], Protocol[T]): ... HydraSupportedType = Union[ _HydraPrimitive, DataClass_, - Type[DataClass_], + type[DataClass_], ListConfig, DictConfig, Enum, _MISSING_TYPE, # Even thought this is redundant with Sequence, it seems to # be needed for pyright to do proper checking of tuple contents - Tuple["HydraSupportedType", ...], + tuple["HydraSupportedType", ...], Sequence["HydraSupportedType"], Mapping[Any, "HydraSupportedType"], ] @@ -206,7 +198,7 @@ class HydraPartialBuilds(Builds[T], HydraPartialMixin[T], Protocol[T]): ... _SupportedViaBuilds = Union[ Partial[Any], range, - Set[Any], + set[Any], timedelta, types.SimpleNamespace, ] @@ -226,10 +218,10 @@ class HydraPartialBuilds(Builds[T], HydraPartialMixin[T], Protocol[T]): ... SupportedPrimitive: TypeAlias = Union[ _SupportedPrimitive, - FrozenSet["SupportedPrimitive"], + frozenset["SupportedPrimitive"], # Even thought this is redundant with Sequence, it seems to # be needed for pyright to do proper checking of tuple contents - Tuple["SupportedPrimitive", ...], + tuple["SupportedPrimitive", ...], # Mutable generic containers need to be invariant, so # we have to settle for Sequence/Mapping. While this # is overly permissive in terms of sequence-type, it @@ -244,7 +236,7 @@ class HydraPartialBuilds(Builds[T], HydraPartialMixin[T], Protocol[T]): ... CustomConfigType: TypeAlias = Union[ T2, HydraSupportedType, - Tuple["CustomConfigType[T2]", ...], + tuple["CustomConfigType[T2]", ...], Sequence["CustomConfigType[T2]"], Mapping[Any, "CustomConfigType[T2]"], Partial["CustomConfigType[T2]"], @@ -276,9 +268,9 @@ class MyBuilds(BuildsFn[CustomConfigType[MyType]]): Builds[Callable[[T4], T4]], PartialBuilds[Callable[[T4], T4]], Just[Callable[[T4], T4]], - Type[Builds[Callable[[T4], T4]]], - Type[PartialBuilds[Callable[[T4], T4]]], - Type[Just[Callable[[T4], T4]]], + type[Builds[Callable[[T4], T4]]], + type[PartialBuilds[Callable[[T4], T4]]], + type[Just[Callable[[T4], T4]]], Callable[[T4], T4], str, ] @@ -287,9 +279,9 @@ class MyBuilds(BuildsFn[CustomConfigType[MyType]]): ZenWrappers: TypeAlias = Union[ZenWrapper[T4], Sequence[ZenWrapper[T4]]] -DefaultsList = List[ +DefaultsList = list[ Union[ - str, DataClass_, Type[DataClass_], Mapping[str, Union[None, str, Sequence[str]]] + str, DataClass_, type[DataClass_], Mapping[str, Union[None, str, Sequence[str]]] ] ] @@ -402,8 +394,8 @@ class ZenConvert(TypedDict, total=False): class _AllPyDataclassOptions(TypedDict, total=False): cls_name: str - namespace: Optional[Dict[str, Any]] - bases: Tuple[Type[DataClass_], ...] + namespace: Optional[dict[str, Any]] + bases: tuple[type[DataClass_], ...] init: bool repr: bool eq: bool @@ -608,7 +600,7 @@ class DataclassOptions(_Py312Dataclass, total=False): target_repr: bool -def _permitted_keys(typed_dict: Any) -> FrozenSet[str]: +def _permitted_keys(typed_dict: Any) -> frozenset[str]: return typed_dict.__required_keys__ | typed_dict.__optional_keys__ diff --git a/src/hydra_zen/wrapper/_implementations.py b/src/hydra_zen/wrapper/_implementations.py index b1ee669c6..c74c0f00c 100644 --- a/src/hydra_zen/wrapper/_implementations.py +++ b/src/hydra_zen/wrapper/_implementations.py @@ -4,6 +4,7 @@ import warnings from collections import defaultdict +from collections.abc import Generator, Iterable, Mapping, Sequence from contextvars import copy_context from copy import deepcopy from functools import partial, wraps @@ -13,18 +14,9 @@ Any, Callable, DefaultDict, - Dict, - FrozenSet, - Generator, + Final, Generic, - Iterable, - List, - Mapping, Optional, - Sequence, - Set, - Tuple, - Type, TypeVar, Union, cast, @@ -36,7 +28,6 @@ from hydra.core.config_store import ConfigStore from omegaconf import DictConfig, ListConfig, OmegaConf from typing_extensions import ( - Final, Literal, ParamSpec, Protocol, @@ -80,12 +71,12 @@ _UNSPECIFIED_: Any = object() -_SUPPORTED_INSTANTIATION_TYPES: Tuple[Any, ...] = (dict, DictConfig, list, ListConfig) +_SUPPORTED_INSTANTIATION_TYPES: tuple[Any, ...] = (dict, DictConfig, list, ListConfig) ConfigLike: TypeAlias = Union[ DataClass_, - Type[DataClass_], - Dict[Any, Any], + type[DataClass_], + dict[Any, Any], DictConfig, ] @@ -234,7 +225,7 @@ def __init__( ) self._run_in_context: bool = run_in_context - self._exclude: Set[str] + self._exclude: set[str] if exclude is None: self._exclude = set() @@ -286,9 +277,9 @@ def _normalize_cfg( self, cfg: Union[ DataClass_, - Type[DataClass_], - Dict[Any, Any], - List[Any], + type[DataClass_], + dict[Any, Any], + list[Any], ListConfig, DictConfig, str, @@ -338,7 +329,7 @@ def validate(self, __cfg: Union[ConfigLike, str]) -> None: p.kind is p.POSITIONAL_ONLY for p in self.parameters.values() ) - _args_: List[Any] = getattr(cfg, "_args_", []) + _args_: list[Any] = getattr(cfg, "_args_", []) if not isinstance(_args_, Sequence): raise HydraZenValidationError( @@ -352,7 +343,7 @@ def validate(self, __cfg: Union[ConfigLike, str]) -> None: f"arguments via `_args_`." ) - missing_params: List[str] = [] + missing_params: list[str] = [] for name, param in self.parameters.items(): if name in self._exclude: continue @@ -538,7 +529,7 @@ def zen( *, unpack_kwargs: bool = ..., pre_call: PreCall = ..., - ZenWrapper: Type[Zen[Any, Any]] = ..., + ZenWrapper: type[Zen[Any, Any]] = ..., resolve_pre_call: bool = ..., run_in_context: bool = ..., exclude: Optional[Union[str, Iterable[str]]] = ..., @@ -553,7 +544,7 @@ def zen( unpack_kwargs: bool = ..., pre_call: PreCall = ..., resolve_pre_call: bool = ..., - ZenWrapper: Type[Zen[Any, Any]] = ..., + ZenWrapper: type[Zen[Any, Any]] = ..., run_in_context: bool = ..., exclude: Optional[Union[str, Iterable[str]]] = ..., instantiation_wrapper: Optional[Callable[[F2], F2]] = ..., @@ -568,7 +559,7 @@ def zen( exclude: Optional[Union[str, Iterable[str]]] = None, resolve_pre_call: bool = True, run_in_context: bool = False, - ZenWrapper: Type[Zen[Any, Any]] = Zen, + ZenWrapper: type[Zen[Any, Any]] = Zen, instantiation_wrapper: Optional[Callable[[F2], F2]] = None, ) -> Union[Callable[[Callable[P2, R2]], Zen[P2, R2]], Zen[P, R]]: r"""zen(func, /, pre_call, ZenWrapper) @@ -860,14 +851,14 @@ def default_to_config( target: Union[ Callable[..., Any], DataClass_, - List[Any], - Dict[Any, Any], + list[Any], + dict[Any, Any], ListConfig, DictConfig, ], - CustomBuildsFn: Type["BuildsFn[Any]"] = DefaultBuilds, + CustomBuildsFn: type["BuildsFn[Any]"] = DefaultBuilds, **kw: Any, -) -> Union[DataClass_, Type[DataClass_], ListConfig, DictConfig]: +) -> Union[DataClass_, type[DataClass_], ListConfig, DictConfig]: """Creates a config that describes `target`. This function is designed to selectively apply `hydra_zen.builds` or @@ -957,7 +948,7 @@ def default_to_config( else: t = cast(Callable[..., Any], target) kw.setdefault("populate_full_signature", True) - return cast(Type[DataClass_], CustomBuildsFn.builds(t, **kw)) + return cast(type[DataClass_], CustomBuildsFn.builds(t, **kw)) class _HasName(Protocol): @@ -986,7 +977,7 @@ class _StoreCallSig(TypedDict): group: Union[GroupName, Callable[[Any], GroupName]] package: Optional[Union[str, Callable[[Any], str]]] provider: Optional[str] - __kw: Dict[str, Any] # kwargs passed to to_config + __kw: dict[str, Any] # kwargs passed to to_config to_config: Callable[[Any], Any] @@ -1000,7 +991,7 @@ class _StoreCallSig(TypedDict): __kw={}, ) -_DEFAULT_KEYS: Final[FrozenSet[str]] = frozenset( +_DEFAULT_KEYS: Final[frozenset[str]] = frozenset( _StoreCallSig.__required_keys__ - {"__kw"} ) @@ -1009,7 +1000,7 @@ class _Deferred: __slots__ = ("to_config", "target", "kw") def __init__( - self, to_config: Callable[[F], Node], target: F, kw: Dict[str, Any] + self, to_config: Callable[[F], Node], target: F, kw: dict[str, Any] ) -> None: self.to_config = to_config self.target = target @@ -1432,9 +1423,9 @@ def __init__( # The following attributes are mirrored across store instances that are # created via the 'self-partialing' process - self._internal_repo: Dict[Tuple[GroupName, NodeName], StoreEntry] = {} + self._internal_repo: dict[tuple[GroupName, NodeName], StoreEntry] = {} # Internal repo entries that have yet to be added to Hydra's config store - self._queue: Set[Tuple[GroupName, NodeName]] = set() + self._queue: set[tuple[GroupName, NodeName]] = set() self._deferred_to_config = deferred_to_config self._deferred_store = deferred_hydra_store @@ -1446,7 +1437,7 @@ def __init__( def __repr__(self) -> str: # TODO: nicer repr? - groups_contents: DefaultDict[Optional[str], List[str]] = defaultdict(list) + groups_contents: DefaultDict[Optional[str], list[str]] = defaultdict(list) for grp, name in self._internal_repo: groups_contents[grp].append(name) @@ -1751,13 +1742,13 @@ def copy_with_mapped_groups( @property def groups(self) -> Sequence[GroupName]: """Returns a sorted list of the groups registered with this store""" - set_: Set[GroupName] = set(group for group, _ in self._internal_repo) + set_: set[GroupName] = {group for group, _ in self._internal_repo} if None in set_: set_.remove(None) - no_none = cast(Set[str], set_) + no_none = cast(set[str], set_) return [None] + sorted(no_none) else: - no_none = cast(Set[str], set_) + no_none = cast(set[str], set_) return sorted(no_none) def enqueue_all(self) -> None: @@ -1893,12 +1884,12 @@ def __ior__(self: Self, other: "ZenStore") -> Self: return self @overload - def __getitem__(self, key: Tuple[GroupName, NodeName]) -> Node: ... + def __getitem__(self, key: tuple[GroupName, NodeName]) -> Node: ... @overload - def __getitem__(self, key: GroupName) -> Dict[Tuple[GroupName, NodeName], Node]: ... + def __getitem__(self, key: GroupName) -> dict[tuple[GroupName, NodeName], Node]: ... - def __getitem__(self, key: Union[GroupName, Tuple[GroupName, NodeName]]) -> Node: + def __getitem__(self, key: Union[GroupName, tuple[GroupName, NodeName]]) -> Node: """Access a entry's config node by specifying `(group, name)`. Or, access a mapping of `(group, name) -> node` for all nodes in a specified group, including nodes within subgroups. @@ -1951,7 +1942,7 @@ def __getitem__(self, key: Union[GroupName, Tuple[GroupName, NodeName]]) -> Node } return _resolve_node(self._internal_repo[key], copy=False)["node"] - def __delitem__(self, key: Tuple[GroupName, NodeName]) -> None: + def __delitem__(self, key: tuple[GroupName, NodeName]) -> None: del self._internal_repo[key] self._queue.discard(key) @@ -2011,7 +2002,7 @@ def _set_entry(self, __entry: StoreEntry, overwrite: bool) -> None: if not self._deferred_store: self.add_to_hydra_store() - def __contains__(self, key: Union[GroupName, Tuple[GroupName, NodeName]]) -> bool: + def __contains__(self, key: Union[GroupName, tuple[GroupName, NodeName]]) -> bool: """Checks if group or (group, node-name) exists in zen-store.""" if key is None: return any(k[0] is None for k in self._internal_repo) # pragma: no branch diff --git a/tests/annotations/declarations.py b/tests/annotations/declarations.py index cbd98bf3f..b199f89c1 100644 --- a/tests/annotations/declarations.py +++ b/tests/annotations/declarations.py @@ -18,18 +18,7 @@ from enum import Enum from functools import partial from pathlib import Path -from typing import ( - Any, - Callable, - Dict, - List, - Mapping, - Optional, - Tuple, - Type, - TypeVar, - Union, -) +from typing import Any, Callable, List, Mapping, Optional, Tuple, Type, TypeVar, Union from hydra.core.utils import JobReturn from omegaconf import MISSING, DictConfig, ListConfig @@ -1216,10 +1205,10 @@ class SubStore(ZenStore): ... assert_type(substore1, SubStore) - assert_type(x, Dict[str, int]) + assert_type(x, dict[str, int]) # check __getitem__ - assert_type(store["group"], Dict[Tuple[Optional[str], str], Any]) + assert_type(store["group"], dict[Tuple[Optional[str], str], Any]) assert_type(store[None, "name"], Any) assert_type(store["group", "name"], Any) store["name", "group", "bad"] # type: ignore @@ -1453,14 +1442,14 @@ def foo(x: int, y: str): ... Conf = kwargs_of(foo) reveal_type( Conf, - expected_text="type[BuildsWithSig[type[Dict[str, Any]], (x: int, y: str)]]", + expected_text="type[BuildsWithSig[type[dict[str, Any]], (x: int, y: str)]]", ) Conf2 = kwargs_of(foo, zen_exclude=[0]) - reveal_type(Conf2, expected_text="type[Builds[type[Dict[str, Any]]]]") + reveal_type(Conf2, expected_text="type[Builds[type[dict[str, Any]]]]") Conf3 = kwargs_of(foo, x=1) - reveal_type(Conf3, expected_text="type[Builds[type[Dict[str, Any]]]]") + reveal_type(Conf3, expected_text="type[Builds[type[dict[str, Any]]]]") class NotSupported: ... @@ -1470,42 +1459,42 @@ def bar(x: int, y: str, z: bool): ... reveal_type( kwargs_of(bar, zen_exclude=()), - expected_text="type[BuildsWithSig[type[Dict[str, Any]], (x: int, y: str, z: bool)]]", + expected_text="type[BuildsWithSig[type[dict[str, Any]], (x: int, y: str, z: bool)]]", ) reveal_type( kwargs_of(bar, zen_exclude=(0,)), - expected_text="type[BuildsWithSig[type[Dict[str, Any]], (y: str, z: bool)]]", + expected_text="type[BuildsWithSig[type[dict[str, Any]], (y: str, z: bool)]]", ) reveal_type( kwargs_of(bar, zen_exclude=(0, 1)), - expected_text="type[BuildsWithSig[type[Dict[str, Any]], (z: bool)]]", + expected_text="type[BuildsWithSig[type[dict[str, Any]], (z: bool)]]", ) reveal_type( kwargs_of(bar, zen_exclude=(0, 1, 2)), - expected_text="type[BuildsWithSig[type[Dict[str, Any]], ()]]", + expected_text="type[BuildsWithSig[type[dict[str, Any]], ()]]", ) reveal_type( kwargs_of(bar, zen_exclude=(0, 1, 2, 3)), - expected_text="type[Builds[type[Dict[str, Any]]]]", + expected_text="type[Builds[type[dict[str, Any]]]]", ) reveal_type( kwargs_of(bar, zen_exclude=(1,)), - expected_text="type[Builds[type[Dict[str, Any]]]]", + expected_text="type[Builds[type[dict[str, Any]]]]", ) reveal_type( kwargs_of(bar, zen_exclude=[0]), - expected_text="type[Builds[type[Dict[str, Any]]]]", + expected_text="type[Builds[type[dict[str, Any]]]]", ) reveal_type( kwargs_of(bar, x=1, zen_exclude=(0,)), - expected_text="type[Builds[type[Dict[str, Any]]]]", + expected_text="type[Builds[type[dict[str, Any]]]]", ) diff --git a/tests/conftest.py b/tests/conftest.py index f579b2926..e529e9fc7 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -6,8 +6,9 @@ import os import sys import tempfile +from collections.abc import Iterable from copy import deepcopy -from typing import Dict, Iterable, Optional +from typing import Optional import hypothesis.strategies as st import pytest @@ -47,17 +48,7 @@ # suite runs against these paths being enabled importlib.import_module(_module_name) -if sys.version_info > (3, 6): - collect_ignore_glob.append("*py36*") - -if sys.version_info < (3, 7): - collect_ignore_glob.append("**/*test_sequence_coercion.py") - -if sys.version_info < (3, 8): - collect_ignore_glob.append("*py38*") - -if sys.version_info < (3, 9): - collect_ignore_glob.append("*py39*") +collect_ignore_glob.append("*py36*") if sys.version_info < (3, 10): collect_ignore_glob.append("*py310*") @@ -87,7 +78,7 @@ def clean_store() -> Iterable[dict]: @pytest.fixture() -def version_base() -> Dict[str, Optional[str]]: +def version_base() -> dict[str, Optional[str]]: """Return version_base according to local version, or empty dict for versions preceding version_base""" return ( diff --git a/tests/custom_strategies.py b/tests/custom_strategies.py index bcdee1346..38eefb4e8 100644 --- a/tests/custom_strategies.py +++ b/tests/custom_strategies.py @@ -1,18 +1,8 @@ # Copyright (c) 2025 Massachusetts Institute of Technology # SPDX-License-Identifier: MIT import string -from typing import ( - Any, - Deque, - Dict, - List, - Optional, - Sequence, - Tuple, - TypeVar, - Union, - cast, -) +from collections.abc import Sequence +from typing import Any, Deque, Optional, TypeVar, Union, cast import hypothesis.strategies as st @@ -23,8 +13,8 @@ __all__ = ["valid_builds_args", "partitions", "everything_except"] -_Sequence = Union[List, Tuple, Deque] -T = TypeVar("T", bound=Union[_Sequence, Dict[str, Any]]) +_Sequence = Union[list, tuple, Deque] +T = TypeVar("T", bound=Union[_Sequence, dict[str, Any]]) def _wrapper(obj): @@ -42,7 +32,7 @@ def _wrapper(obj): slots_strat = st.booleans() -def _compat_slots(conf: Dict[str, Any]): +def _compat_slots(conf: dict[str, Any]): # dataclass has some hard rules about a frozen dataclass inheriting # from a non-frozen one anf vice versa. Let's avoid this @@ -96,7 +86,7 @@ def _compat_slots(conf: Dict[str, Any]): ) -def _compat_frozen(conf: Dict[str, Any]): +def _compat_frozen(conf: dict[str, Any]): # dataclass has some hard rules about a frozen dataclass inheriting # from a non-frozen one anf vice versa. Let's avoid this if conf.get("frozen", None) is True and conf.get("builds_bases", ()): @@ -129,7 +119,7 @@ def valid_builds_args(*required: str, excluded: Sequence[str] = ()): @st.composite -def _partition(draw: st.DrawFn, collection: T, ordered: bool) -> Tuple[T, T]: +def _partition(draw: st.DrawFn, collection: T, ordered: bool) -> tuple[T, T]: if isinstance(collection, dict): keys = list(collection) else: @@ -150,11 +140,11 @@ def _partition(draw: st.DrawFn, collection: T, ordered: bool) -> Tuple[T, T]: def partitions( collection: Union[T, st.SearchStrategy[T]], ordered: bool = True -) -> st.SearchStrategy[Tuple[T, T]]: +) -> st.SearchStrategy[tuple[T, T]]: """Randomly partitions a collection or dictionary into two partitions.""" if isinstance(collection, st.SearchStrategy): return collection.flatmap(lambda x: _partition(x, ordered=ordered)) - return cast(st.SearchStrategy[Tuple[T, T]], _partition(collection, ordered)) + return cast(st.SearchStrategy[tuple[T, T]], _partition(collection, ordered)) def everything_except(excluded_types): diff --git a/tests/pyright_utils.py b/tests/pyright_utils.py index f3d4ccb45..d34ea0d36 100644 --- a/tests/pyright_utils.py +++ b/tests/pyright_utils.py @@ -13,7 +13,7 @@ from collections import Counter, defaultdict from contextlib import contextmanager from pathlib import Path -from typing import Any, DefaultDict, Dict, List, Optional, Union +from typing import Any, DefaultDict, Optional, Union from typing_extensions import Literal, NotRequired, TypedDict @@ -60,7 +60,7 @@ class PyrightOutput(TypedDict): version: str time: str - generalDiagnostics: List[Diagnostic] + generalDiagnostics: list[Diagnostic] summary: Summary @@ -105,7 +105,7 @@ def get_docstring_examples(doc: str) -> str: # contains input lines of docstring examples with all indentation # and REPL markers removed - src_lines: List[str] = [] + src_lines: list[str] = [] for source, indent in docstring_re.findall(doc): source: str @@ -151,16 +151,16 @@ def rst_to_code(src: str) -> str: ''' """ - block: Optional[List[str]] = None # lines in code block + block: Optional[list[str]] = None # lines in code block indentation: Optional[str] = None # leading whitespace before .. code-block preamble: Optional[str] = None # python or pycon n = -float("inf") # line no in code block - blocks: List[str] = [] # respective code blocks, each ready for processing + blocks: list[str] = [] # respective code blocks, each ready for processing def add_block( - block: Optional[List[str]], + block: Optional[list[str]], preamble: Optional[str], - blocks: List[str], + blocks: list[str], ): if block: block_str = "\n".join(block) + "\n" @@ -218,14 +218,14 @@ def add_block( def pyright_analyze( *code_objs_and_or_paths: Any, - pyright_config: Optional[Dict[str, Any]] = None, + pyright_config: Optional[dict[str, Any]] = None, scan_docstring: bool = False, path_to_pyright: Union[Path, None] = PYRIGHT_PATH, preamble: str = "", python_version: Optional[str] = None, report_unnecessary_type_ignore_comment: Optional[bool] = None, type_checking_mode: Optional[Literal["basic", "strict"]] = None, -) -> List[PyrightOutput]: +) -> list[PyrightOutput]: r""" Scan one or more Python objects, docstrings, or files with pyright. @@ -416,7 +416,7 @@ def pyright_analyze( if type_checking_mode is not None: pyright_config["typeCheckingMode"] = type_checking_mode - sources: List[Optional[str]] = [] + sources: list[Optional[str]] = [] for code_or_path in code_objs_and_or_paths: if scan_docstring and ( isinstance(code_or_path, (Path, str)) @@ -455,7 +455,7 @@ def pyright_analyze( if preamble and not preamble.endswith("\n"): preamble = preamble + "\n" if not scan_docstring: - source = preamble + textwrap.dedent((inspect.getsource(code_or_path))) + source = preamble + textwrap.dedent(inspect.getsource(code_or_path)) else: docstring = inspect.getdoc(code_or_path) assert docstring is not None @@ -500,7 +500,7 @@ def pyright_analyze( out = scan["generalDiagnostics"] - diagnostics_by_file: DefaultDict[int, List[Diagnostic]] = defaultdict(list) + diagnostics_by_file: DefaultDict[int, list[Diagnostic]] = defaultdict(list) for item in out: file_path = Path(item["file"]) @@ -509,7 +509,7 @@ def pyright_analyze( diagnostic["file"] = file_path.name diagnostics_by_file[file_index].append(diagnostic) - results: List[PyrightOutput] = [] + results: list[PyrightOutput] = [] for n in range(len(code_objs_and_or_paths)): severities = Counter(d["severity"] for d in diagnostics_by_file[n]) @@ -531,7 +531,7 @@ def pyright_analyze( return results -def list_error_messages(results: PyrightOutput) -> List[str]: +def list_error_messages(results: PyrightOutput) -> list[str]: """A convenience function that returns a list of error messages reported by pyright.""" return [ f"(line start) {e['range']['start']['line']}: {e['message']}" diff --git a/tests/test_custom_strategies.py b/tests/test_custom_strategies.py index 14630368a..04379e078 100644 --- a/tests/test_custom_strategies.py +++ b/tests/test_custom_strategies.py @@ -23,11 +23,11 @@ def test_valid_builds_args_passes_builds(kwargs): def test_valid_build_strats_are_exhaustive(): - nameable_builds_args = set( + nameable_builds_args = { n for n, p in inspect.signature(builds).parameters.items() if p.kind is p.KEYWORD_ONLY - ) + } nameable_builds_args.add("zen_exclude") assert nameable_builds_args - {"dataclass_name", "hydra_defaults"} == set( _valid_builds_strats diff --git a/tests/test_dataclass_conversion.py b/tests/test_dataclass_conversion.py index e67603b3f..6f6348f14 100644 --- a/tests/test_dataclass_conversion.py +++ b/tests/test_dataclass_conversion.py @@ -2,7 +2,7 @@ # SPDX-License-Identifier: MIT from dataclasses import MISSING, InitVar, dataclass, field from pathlib import Path -from typing import Any, Callable, List, Type, TypeVar +from typing import Any, Callable, TypeVar import hypothesis.strategies as st import pytest @@ -279,7 +279,7 @@ def test_no_dataclass_conversion( ], ) def test_yes_dataclass_conversion( - config_maker: Callable[[TDataClass], Builds[Type[TDataClass]]], + config_maker: Callable[[TDataClass], Builds[type[TDataClass]]], dataclass_obj: TDataClass, ): out = config_maker(dataclass_obj) @@ -352,9 +352,9 @@ def test_builds_with_positional_arg(): ], ) def test_recursive_dataclass_conversion( - config_maker: Callable[[List[TDataClass]], List[Builds[Type[TDataClass]]]], + config_maker: Callable[[list[TDataClass]], list[Builds[type[TDataClass]]]], dataclass_obj: TDataClass, - as_container: Callable[[T], List[T]], + as_container: Callable[[T], list[T]], ): out = config_maker(as_container(dataclass_obj))[1] # type: ignore inst_out = instantiate(out) diff --git a/tests/test_defaults_list.py b/tests/test_defaults_list.py index cb61f6ea1..6fecc9f71 100644 --- a/tests/test_defaults_list.py +++ b/tests/test_defaults_list.py @@ -3,7 +3,7 @@ import random from functools import partial -from typing import Any, Callable, List +from typing import Any, Callable import hypothesis.strategies as st import pytest @@ -30,7 +30,7 @@ ], ) def test_hydra_defaults_work_as_expected( - fn: Callable, default: Any, overrides: List[str], version_base + fn: Callable, default: Any, overrides: list[str], version_base ): config_store = ConfigStore.instance() config_store.store(group="x", name="a", node=builds(int, 10)) diff --git a/tests/test_docs_typecheck.py b/tests/test_docs_typecheck.py index 22f387f48..a635f3b3c 100644 --- a/tests/test_docs_typecheck.py +++ b/tests/test_docs_typecheck.py @@ -1,7 +1,7 @@ # Copyright (c) 2025 Massachusetts Institute of Technology # SPDX-License-Identifier: MIT from pathlib import Path -from typing import Any, Dict +from typing import Any import pytest @@ -54,7 +54,7 @@ # We use this to cache pyright scan results # so that we can report their results via parameterized tests -PYRIGHT_SCAN_RESULTS: Dict[Any, PyrightOutput] = {} +PYRIGHT_SCAN_RESULTS: dict[Any, PyrightOutput] = {} FUNCS_TO_SCAN = [ diff --git a/tests/test_hydra_behaviors.py b/tests/test_hydra_behaviors.py index 5dc5da7e1..487188109 100644 --- a/tests/test_hydra_behaviors.py +++ b/tests/test_hydra_behaviors.py @@ -1,7 +1,7 @@ # Copyright (c) 2025 Massachusetts Institute of Technology # SPDX-License-Identifier: MIT from dataclasses import dataclass -from typing import Any, List, Tuple +from typing import Any import hypothesis.strategies as st import pytest @@ -93,7 +93,7 @@ class A: ], ) def test_hydra_convert( - convert: str, expected_types: List[type], via_hydrated_dataclass: bool + convert: str, expected_types: list[type], via_hydrated_dataclass: bool ): """Tests that the `hydra_convert` parameter produces the expected/documented behavior in hydra.""" @@ -198,7 +198,7 @@ class A: assert out == {"x": {"_target_": target_path, "y": 1}} -def f(x: Tuple[int]): +def f(x: tuple[int]): return x @@ -211,7 +211,7 @@ def g(x: C): return x -def g2(x: List[C]): +def g2(x: list[C]): return x diff --git a/tests/test_just.py b/tests/test_just.py index 4ae475a52..f35798b04 100644 --- a/tests/test_just.py +++ b/tests/test_just.py @@ -24,7 +24,7 @@ def f(x: int): pass -@functools.lru_cache(maxsize=None) +@functools.cache def func_with_cache(x: int): pass diff --git a/tests/test_kwargs_of.py b/tests/test_kwargs_of.py index a7caed3e4..d89ed675c 100644 --- a/tests/test_kwargs_of.py +++ b/tests/test_kwargs_of.py @@ -39,7 +39,7 @@ class Moo(BuildsFn): Conf1 = kwargs_of((lambda: None), zen_dataclass={"cls_name": "foo"}) assert Conf1.__name__ == "foo" - Conf2 = Moo.kwargs_of((lambda: None)) + Conf2 = Moo.kwargs_of(lambda: None) assert Conf2.__name__ == "bar" diff --git a/tests/test_make_config.py b/tests/test_make_config.py index a0ecb78ab..35b4cc415 100644 --- a/tests/test_make_config.py +++ b/tests/test_make_config.py @@ -4,7 +4,7 @@ import string from enum import Enum from itertools import chain -from typing import Any, Callable, Tuple, Union, get_type_hints +from typing import Any, Callable, Union, get_type_hints import hypothesis.strategies as st import pytest @@ -93,7 +93,7 @@ def test_validate_redundant_args( st.sampled_from(string.ascii_lowercase), min_size=2, max_size=2, unique=True ).map(lambda x: (x[0], ZenField(name=x[1]))) ) -def test_validate_conflicting_kwarg_name(name_and_field: Tuple[str, ZenField]): +def test_validate_conflicting_kwarg_name(name_and_field: tuple[str, ZenField]): name, misnamed_field = name_and_field with pytest.raises(ValueError): make_config(**{name: misnamed_field}) @@ -115,7 +115,7 @@ class A: @example(str) @example(bool) @example(builds(int)) -@example(Tuple[int, str, bool]) +@example(tuple[int, str, bool]) @example(Callable[[int], int]) @example(Union[Callable, int]) @given(hint=st.from_type(type)) diff --git a/tests/test_py39.py b/tests/test_py39.py index 6e141e03c..8c907037f 100644 --- a/tests/test_py39.py +++ b/tests/test_py39.py @@ -1,7 +1,7 @@ # Copyright (c) 2025 Massachusetts Institute of Technology # SPDX-License-Identifier: MIT from dataclasses import dataclass -from typing import Any, Dict, List, Tuple +from typing import Any import pytest from omegaconf import OmegaConf @@ -12,9 +12,9 @@ @pytest.mark.parametrize( "in_type, expected_type", [ - (list[int], List[int]), - (tuple[str, str], Tuple[str, str]), - (dict[str, int], Dict[str, int]), + (list[int], list[int]), + (tuple[str, str], tuple[str, str]), + (dict[str, int], dict[str, int]), (set[str], Any), ], ) diff --git a/tests/test_pyright_utils.py b/tests/test_pyright_utils.py index c5b8390ed..5d9df771d 100644 --- a/tests/test_pyright_utils.py +++ b/tests/test_pyright_utils.py @@ -92,7 +92,7 @@ def print_file(x: int): def strip_interspacing(x: str): - return "\n".join((s for s in x.splitlines() if s)) + return "\n".join(s for s in x.splitlines() if s) @pytest.mark.parametrize( diff --git a/tests/test_roundtrips.py b/tests/test_roundtrips.py index 6dc0b5735..c3111e92e 100644 --- a/tests/test_roundtrips.py +++ b/tests/test_roundtrips.py @@ -11,7 +11,7 @@ import string from collections import Counter, defaultdict, deque from dataclasses import dataclass -from typing import Any, Dict, Generic, List, Optional, TypeVar +from typing import Any, Generic, Optional, TypeVar import hypothesis.strategies as st import pytest @@ -52,8 +52,8 @@ def test_builds_roundtrip(kwargs, full_sig: bool): full_sig=st.booleans(), ) def test_builds_kwargs_roundtrip_with_partial( - partial_kwargs: Dict[str, Any], - call_kwargs: Dict[str, Any], + partial_kwargs: dict[str, Any], + call_kwargs: dict[str, Any], full_sig: bool, ): partial_struct = instantiate( @@ -75,8 +75,8 @@ def test_builds_kwargs_roundtrip_with_partial( full_sig=st.booleans(), ) def test_builds_args_roundtrip_with_partial( - partial_args: List[Any], - call_args: List[Any], + partial_args: list[Any], + call_args: list[Any], full_sig: bool, ): partial_struct = instantiate( diff --git a/tests/test_signature_parsing.py b/tests/test_signature_parsing.py index 6e3c80ad6..dd1118f8e 100644 --- a/tests/test_signature_parsing.py +++ b/tests/test_signature_parsing.py @@ -1,23 +1,13 @@ # Copyright (c) 2025 Massachusetts Institute of Technology # SPDX-License-Identifier: MIT import inspect -import sys from abc import ABC from collections import Counter +from collections.abc import Mapping from dataclasses import dataclass from enum import Enum from inspect import Parameter -from typing import ( - Any, - Callable, - Dict, - List, - Mapping, - Optional, - Tuple, - Type, - get_type_hints, -) +from typing import Any, Callable, Optional, get_type_hints import hypothesis.strategies as st import pytest @@ -190,14 +180,14 @@ def a_func( x: int, y: str, z: bool, - a_tuple: Tuple[str] = ("hi",), + a_tuple: tuple[str] = ("hi",), optional: Optional[int] = None, inferred_optional_str: str = None, inferred_optional_any: Mapping = None, default: float = 100.0, a_function: Callable = func, - a_class: Type[Dict] = dict, - a_dataclass: Type[ADataClass] = ADataClass, + a_class: type[dict] = dict, + a_dataclass: type[ADataClass] = ADataClass, ): pass @@ -208,14 +198,14 @@ def __init__( x: int, y: str, z: bool, - a_tuple: Tuple[str] = ("hi",), + a_tuple: tuple[str] = ("hi",), optional: Optional[int] = None, inferred_optional_str: str = None, inferred_optional_any: Mapping = None, default: float = 100.0, a_function: Callable = func, - a_class: Type[Dict] = dict, - a_dataclass: Type[ADataClass] = ADataClass, + a_class: type[dict] = dict, + a_dataclass: type[ADataClass] = ADataClass, ): pass @@ -225,14 +215,14 @@ def a_class_method( x: int, y: str, z: bool, - a_tuple: Tuple[str] = ("hi",), + a_tuple: tuple[str] = ("hi",), optional: Optional[int] = None, inferred_optional_str: str = None, inferred_optional_any: Mapping = None, default: float = 100.0, a_function: Callable = func, - a_class: Type[Dict] = dict, - a_dataclass: Type[ADataClass] = ADataClass, + a_class: type[dict] = dict, + a_dataclass: type[ADataClass] = ADataClass, ): pass @@ -243,14 +233,14 @@ def __init__( x: int, y: str, z: bool, - a_tuple: Tuple[str] = ("hi",), + a_tuple: tuple[str] = ("hi",), optional: Optional[int] = None, inferred_optional_str: str = None, inferred_optional_any: Mapping = None, default: float = 100.0, a_function: Callable = func, - a_class: Type[Dict] = dict, - a_dataclass: Type[ADataClass] = ADataClass, + a_class: type[dict] = dict, + a_dataclass: type[ADataClass] = ADataClass, ): pass @@ -277,7 +267,7 @@ def test_builds_partial_with_full_sig_excludes_non_specified_params( (var_name, name_to_type[var_name], user_specified_values[var_name]) for var_name in sorted(user_specified_values) ] + [ - ("a_tuple", Tuple[str], ("hi",)), + ("a_tuple", tuple[str], ("hi",)), ("optional", Optional[int], None), ("inferred_optional_str", Optional[str], None), ("inferred_optional_any", Any, None), @@ -390,7 +380,7 @@ def test_builds_widens_non_dataclass_type_with_target(): assert hints["x"] is Any -def func_with_list_annotation(x: List[int]): +def func_with_list_annotation(x: list[int]): return x @@ -432,7 +422,7 @@ def test_type_widening_for_interpolated_field(): assert get_type_hints(C2)["x"] is Any -def use_data(data: List[float]): +def use_data(data: list[float]): return data @@ -557,10 +547,9 @@ def test_Counter(): assert instantiate(builds(Counter, [1, 1, 2, 1])) == Counter([1, 1, 2, 1]) assert instantiate(builds(Counter, a=1, b=2)) == Counter(a=1, b=2) - if sys.version_info > (3, 8): - with pytest.raises(TypeError): - # signature: Counter(iterable=None, /, **kwds) - builds(Counter, [1], [2]) + with pytest.raises(TypeError): + # signature: Counter(iterable=None, /, **kwds) + builds(Counter, [1], [2]) def f_x(x: int): diff --git a/tests/test_store.py b/tests/test_store.py index 7e4906f7c..01b406a24 100644 --- a/tests/test_store.py +++ b/tests/test_store.py @@ -3,11 +3,12 @@ import os import re import sys +from collections.abc import Hashable from contextlib import contextmanager from copy import deepcopy from dataclasses import dataclass from functools import partial -from typing import Any, Callable, Hashable, Optional +from typing import Any, Callable, Optional import hypothesis.strategies as st import pytest diff --git a/tests/test_utils.py b/tests/test_utils.py index 0326729bb..092a5dac0 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -9,15 +9,15 @@ from inspect import signature from pathlib import Path, PosixPath, WindowsPath from typing import ( + Annotated, Any, Callable, Dict, + Final, List, NewType, Optional, - Set, Tuple, - Type, TypeVar, Union, ) @@ -33,8 +33,6 @@ KeyValidationError, ) from typing_extensions import ( - Annotated, - Final, Literal, ParamSpec, Protocol, @@ -45,12 +43,7 @@ ) from hydra_zen import DefaultBuilds, builds, instantiate, mutable_value -from hydra_zen._compatibility import ( - HYDRA_VERSION, - OMEGACONF_VERSION, - Version, - _get_version, -) +from hydra_zen._compatibility import HYDRA_VERSION, Version, _get_version from hydra_zen.structured_configs._utils import ( StrictDataclassOptions, field, @@ -113,8 +106,8 @@ def test_fuzz_safename(obj): def test_mutable_values(): @dataclass class A: - a_list: List[int] = mutable_value([1, 2, 3]) - a_dict: Dict[str, int] = mutable_value(dict(a=1)) + a_list: list[int] = mutable_value([1, 2, 3]) + a_dict: dict[str, int] = mutable_value(dict(a=1)) a = A() assert a.a_dict == {"a": 1} @@ -154,27 +147,27 @@ class SomeProtocol(Protocol[T]): # type: ignore (C, Any), # unsupported primitives (type(None), Any), (set, Any), - (list, (List if OMEGACONF_VERSION < Version(2, 2, 3) else list)), - (tuple, (Any if OMEGACONF_VERSION < Version(2, 2, 3) else tuple)), - (dict, (Dict if OMEGACONF_VERSION < Version(2, 2, 3) else dict)), + (list, list), + (tuple, tuple), + (dict, dict), (callable, Any), (frozenset, Any), - (List, List), - (Dict, Dict), + (List, list), + (Dict, dict), (T, Any), - (List[T], List[Any]), - (Tuple[T, T], Tuple[Any, Any]), + (List[T], list[Any]), + (Tuple[T, T], tuple[Any, Any]), (Callable[P, int], Any), (P, Any), (P.args, Any), # type: ignore (P.kwargs, Any), # type: ignore (Ts, Any), (SomeProtocol[T], Any), - (Tuple[Unpack[Ts]], Tuple[Any, ...]), - (Tuple[Unpack[Ts], int], Tuple[Any, ...]), + (tuple[Unpack[Ts]], tuple[Any, ...]), + (tuple[Unpack[Ts], int], tuple[Any, ...]), pytest.param( - Tuple[str, Unpack[Ts]], - Tuple[Any, ...], + tuple[str, Unpack[Ts]], + tuple[Any, ...], marks=[ pytest.mark.xfail( HYDRA_VERSION < Version(1, 2, 0), @@ -183,8 +176,8 @@ class SomeProtocol(Protocol[T]): # type: ignore ], ), pytest.param( - Tuple[str, Unpack[Ts], int], - Tuple[Any, ...], + tuple[str, Unpack[Ts], int], + tuple[Any, ...], marks=[ pytest.mark.xfail( HYDRA_VERSION < Version(1, 2, 0), @@ -193,18 +186,18 @@ class SomeProtocol(Protocol[T]): # type: ignore ], ), (Annotated[int, int], int), - (Annotated[Tuple[str, str], int], Tuple[str, str]), + (Annotated[tuple[str, str], int], tuple[str, str]), (Annotated[Builds, int], Any), (NewType("I", int), int), - (NewType("S", Tuple[str, str]), Tuple[str, str]), + (NewType("S", tuple[str, str]), tuple[str, str]), (Self, Any), # type: ignore (Literal[1, 2], Any), # unsupported generics - (Type[int], Any), + (type[int], Any), (Builds, Any), (Builds[int], Any), - (Type[Builds[int]], Any), - (Set, Any), - (Set[int], Any), + (type[Builds[int]], Any), + (set, Any), + (set[int], Any), (Final[int], Any), (Callable, Any), (Callable[[int], int], Any), @@ -215,53 +208,56 @@ class SomeProtocol(Protocol[T]): # type: ignore (Union[NoneType, frozenset], Any), (Union[NoneType, int], Optional[int]), # supported Optional (Optional[Color], Optional[Color]), - (Optional[List[Color]], Optional[List[Color]]), + (Optional[list[Color]], Optional[list[Color]]), ( - Optional[List[List[int]]], - Optional[List[List[int]]], + Optional[list[list[int]]], + Optional[list[list[int]]], ), - (List[int], List[int]), # supported containers - (List[frozenset], List[Any]), + (list[int], list[int]), # supported containers + (list[frozenset], list[Any]), ( - List[List[int]], - List[List[int]], + list[list[int]], + list[list[int]], ), - (List[Tuple[int, int]], List[Any]), - (List[T], List[Any]), - (Dict[str, float], Dict[str, float]), - (Dict[C, int], Dict[Any, int]), - (Dict[str, C], Dict[str, Any]), - (Dict[C, C], Dict[Any, Any]), + (list[tuple[int, int]], list[Any]), + (list[T], list[Any]), + (dict[str, float], dict[str, float]), + (dict[C, int], dict[Any, int]), + (dict[str, C], dict[str, Any]), + (dict[C, C], dict[Any, Any]), ( - Dict[str, List[int]], - Dict[str, List[int]], + dict[str, list[int]], + dict[str, list[int]], ), - (Tuple[str], Tuple[str]), - (Tuple[str, ...], Tuple[str, ...]), - (Tuple[str, str, str], Tuple[str, str, str]), + (tuple[str], tuple[str]), + (tuple[str, ...], tuple[str, ...]), + (tuple[str, str, str], tuple[str, str, str]), ( - Tuple[List[int]], - (Tuple[List[int]]), + tuple[list[int]], + (tuple[list[int]]), ), - (Union[NoneType, Tuple[int, int]], Optional[Tuple[int, int]]), - (Union[Tuple[int, int], NoneType], Optional[Tuple[int, int]]), + (Union[NoneType, tuple[int, int]], Optional[tuple[int, int]]), + (Union[tuple[int, int], NoneType], Optional[tuple[int, int]]), ( - List[Dict[str, List[int]]], - List[Dict[str, List[int]]], + list[dict[str, list[int]]], + list[dict[str, list[int]]], ), ( - List[List[Type[int]]], - List[List[Any]], + list[list[type[int]]], + list[list[Any]], ), - (Tuple[Tuple[int, ...], ...], Tuple[Any, ...]), - (Optional[Tuple[Tuple[int, ...], ...]], Optional[Tuple[Any, ...]]), - (InitVar[List[frozenset]], Any if sys.version_info < (3, 8) else List[Any]), + (tuple[tuple[int, ...], ...], tuple[Any, ...]), + (Optional[tuple[tuple[int, ...], ...]], Optional[tuple[Any, ...]]), + (InitVar[list[frozenset]], Any if sys.version_info < (3, 8) else list[Any]), ], ) def test_sanitized_type_expected_behavior(in_type, expected_type): assert DefaultBuilds._sanitized_type(in_type) == expected_type, in_type - if in_type != expected_type: + if in_type != expected_type and (in_type, expected_type) not in [ + (List, list), + (Dict, dict), + ]: # In cases where we change the type, it should be because omegaconf # doesn't support that annotation. # This check will help catch cases where omegaconf/hydra has added support for @@ -293,7 +289,11 @@ class Tmp: def test_tuple_annotation_normalization(): - assert DefaultBuilds._sanitized_type(Tuple[int, str, int]) is Tuple[Any, Any, Any] + x = DefaultBuilds._sanitized_type(Tuple[int, str, int]) + assert tuple[Any, Any, Any] == tuple[Any, Any, Any], "yee" + assert ( + DefaultBuilds._sanitized_type(Tuple[int, str, int]) == tuple[Any, Any, Any] + ), x def f_list(x: List): diff --git a/tests/test_value_conversion.py b/tests/test_value_conversion.py index 5a0e14eec..2f70772dd 100644 --- a/tests/test_value_conversion.py +++ b/tests/test_value_conversion.py @@ -4,12 +4,13 @@ import pickle import string from collections import Counter, defaultdict, deque +from collections.abc import Iterable from dataclasses import dataclass, field from datetime import timedelta from enum import Enum from functools import partial from pathlib import Path -from typing import Any, Callable, Dict, FrozenSet, Iterable, List, Set, Union +from typing import Any, Callable, Union import hypothesis.strategies as st import pytest @@ -53,15 +54,15 @@ class Shake(Enum): str, type(None), Shake, - List[Union[int, List[int], Dict[int, int]]], - Dict[int, Union[int, List[int], Dict[int, int]]], + list[Union[int, list[int], dict[int, int]]], + dict[int, Union[int, list[int], dict[int, int]]], ListConfig, DictConfig, # hydra-zen supported primitives set, frozenset, - FrozenSet[Union[int, complex]], - Set[Union[int, complex, Path]], + frozenset[Union[int, complex]], + set[Union[int, complex, Path]], complex, Path, bytes, @@ -128,7 +129,7 @@ def test_value_supported_via_config_maker_functions( Blistconfig = pik_blds( dict, x=ListConfig([1, {"a": 2}]), zen_dataclass={"cls_name": "Blistconfig"} ) -Bset = pik_blds(dict, x=set([1, 2]), zen_dataclass={"cls_name": "Bset"}) +Bset = pik_blds(dict, x={1, 2}, zen_dataclass={"cls_name": "Bset"}) Bfrozenset = pik_blds( dict, x=frozenset([1j, 2j]), zen_dataclass={"cls_name": "Bfrozenset"} ) @@ -327,8 +328,8 @@ class C: @dataclass class A_builds_populate_sig_with_default_factory: z: Any - x_list: List[int] = field(default_factory=lambda: list([1, 0, 1, 0, 1])) - x_dict: Dict[str, int] = field(default_factory=lambda: dict({"K_DEFAULT": 10101})) + x_list: list[int] = field(default_factory=lambda: list([1, 0, 1, 0, 1])) + x_dict: dict[str, int] = field(default_factory=lambda: dict({"K_DEFAULT": 10101})) y: bool = False @@ -380,7 +381,7 @@ def test_builds_populate_sig_with_default_factory( class A_auto_config_for_dataclass_fields: complex_factory: Any = mutable_value(1 + 2j) complex_: complex = 2 + 4j - list_of_stuff: List[Any] = field( + list_of_stuff: list[Any] = field( default_factory=lambda: list([1 + 2j, Path.home()]) ) fn_factory: Callable[[Iterable[int]], int] = field(default_factory=lambda: sum) diff --git a/tests/test_zen.py b/tests/test_zen.py index 98627e8f5..d4a76db1b 100644 --- a/tests/test_zen.py +++ b/tests/test_zen.py @@ -6,7 +6,7 @@ import random import sys from dataclasses import dataclass -from typing import Any, Tuple +from typing import Any import pytest from hypothesis import example, given, strategies as st @@ -288,7 +288,7 @@ def test_custom_zen_wrapper(x, wrap_mode): class MyZen(Zen): CFG_NAME: str = "secret_cfg" - def __call__(self, cfg) -> Tuple[Any, str]: + def __call__(self, cfg) -> tuple[Any, str]: return (super().__call__(cfg), "moo") if wrap_mode == "decorator": diff --git a/tests/test_zen_context_isolation.py b/tests/test_zen_context_isolation.py index 424fd5ed2..c35b389d8 100644 --- a/tests/test_zen_context_isolation.py +++ b/tests/test_zen_context_isolation.py @@ -4,15 +4,15 @@ import random from contextvars import ContextVar from dataclasses import dataclass -from typing import Any, Dict, Optional, Type +from typing import Any, Optional import pytest from hydra_zen import zen from hydra_zen.errors import HydraZenValidationError -config: ContextVar[Optional[Dict[str, Any]]] = ContextVar("config", default=None) -var: ContextVar[Dict[str, Any]] = ContextVar("var", default=dict()) +config: ContextVar[Optional[dict[str, Any]]] = ContextVar("config", default=None) +var: ContextVar[dict[str, Any]] = ContextVar("var", default=dict()) @pytest.fixture(autouse=True) @@ -51,7 +51,7 @@ def __call__(self, fn) -> Any: TrackCall, ], ) -def test_context_isolation(run_in_context: bool, wrapper: Optional[Type[TrackCall]]): +def test_context_isolation(run_in_context: bool, wrapper: Optional[type[TrackCall]]): def foo(x: str, zen_cfg): config.set(zen_cfg) conf = var.get().copy()