Skip to content

Commit a404a1b

Browse files
committed
Cleaned up TypeVars
1 parent 143134b commit a404a1b

File tree

9 files changed

+70
-67
lines changed

9 files changed

+70
-67
lines changed

src/omnipy/api/protocols/public/data.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@
44

55
from omnipy.api.protocols.private.log import CanLog
66

7-
ModelT = TypeVar('ModelT')
7+
_ModelT = TypeVar('_ModelT')
88

99

10-
class IsDataset(Protocol[ModelT]):
10+
class IsDataset(Protocol[_ModelT]):
1111
"""
1212
Dict-based container of data files that follow a specific Model
1313
"""
@@ -21,7 +21,7 @@ def __init__(
2121
...
2222

2323
@classmethod
24-
def get_model_class(cls) -> Type[ModelT]:
24+
def get_model_class(cls) -> Type[_ModelT]:
2525
"""
2626
Returns the concrete Model class used for all data files in the dataset, e.g.:
2727
`Model[list[int]]`
@@ -49,18 +49,18 @@ def from_json(self,
4949
def to_json_schema(cls, pretty=True) -> str | dict[str, str]:
5050
...
5151

52-
def as_multi_model_dataset(self) -> 'MultiModelDataset[ModelT]':
52+
def as_multi_model_dataset(self) -> 'MultiModelDataset[_ModelT]':
5353
...
5454

5555

56-
class MultiModelDataset(Protocol[ModelT]):
56+
class MultiModelDataset(Protocol[_ModelT]):
5757
"""
5858
Variant of Dataset that allows custom models to be set on individual data files
5959
"""
60-
def set_model(self, data_file: str, model: ModelT) -> None:
60+
def set_model(self, data_file: str, model: _ModelT) -> None:
6161
...
6262

63-
def get_model(self, data_file: str) -> ModelT:
63+
def get_model(self, data_file: str) -> _ModelT:
6464
...
6565

6666

src/omnipy/data/dataset.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -604,20 +604,20 @@ def _to_data_if_model(data_obj: Any):
604604
return data_obj
605605

606606

607-
KwargValT = TypeVar('KwargValT', bound=object)
608-
ParamModelT = TypeVar('ParamModelT', bound=ParamModel)
609-
ListOfParamModelT = TypeVar('ListOfParamModelT', bound=ListOfParamModel)
607+
_KwargValT = TypeVar('_KwargValT', bound=object)
608+
_ParamModelT = TypeVar('_ParamModelT', bound=ParamModel)
609+
_ListOfParamModelT = TypeVar('_ListOfParamModelT', bound=ListOfParamModel)
610610

611611
ParamModelSuperKwargsType: TypeAlias = \
612-
dict[str, dict[str, ParamModelT | DataWithParams[ParamModelT, KwargValT]]]
612+
dict[str, dict[str, _ParamModelT | DataWithParams[_ParamModelT, _KwargValT]]]
613613

614614
ListOfParamModelSuperKwargsType: TypeAlias = \
615-
dict[str, dict[str, list[ListOfParamModelT | DataWithParams[ListOfParamModelT, KwargValT]]]]
615+
dict[str, dict[str, list[_ListOfParamModelT | DataWithParams[_ListOfParamModelT, _KwargValT]]]]
616616

617617

618-
class ParamDataset(Dataset[ParamModelT | DataWithParams[ParamModelT, KwargValT]],
619-
Generic[ParamModelT, KwargValT]):
620-
def _init(self, super_kwargs: ParamModelSuperKwargsType, **kwargs: KwargValT) -> None:
618+
class ParamDataset(Dataset[_ParamModelT | DataWithParams[_ParamModelT, _KwargValT]],
619+
Generic[_ParamModelT, _KwargValT]):
620+
def _init(self, super_kwargs: ParamModelSuperKwargsType, **kwargs: _KwargValT) -> None:
621621
if kwargs and DATA_KEY in super_kwargs:
622622
super_kwargs[DATA_KEY] = {
623623
key: DataWithParams(data=val, params=kwargs)
@@ -627,7 +627,7 @@ def _init(self, super_kwargs: ParamModelSuperKwargsType, **kwargs: KwargValT) ->
627627
def from_data(self,
628628
data: dict[str, Any] | Iterator[tuple[str, Any]],
629629
update: bool = True,
630-
**kwargs: KwargValT) -> None:
630+
**kwargs: _KwargValT) -> None:
631631
if kwargs:
632632

633633
def callback_func(model: ModelT, contents: Any):
@@ -640,7 +640,7 @@ def callback_func(model: ModelT, contents: Any):
640640
def from_json(self,
641641
data: Mapping[str, str] | Iterable[tuple[str, str]],
642642
update: bool = True,
643-
**kwargs: KwargValT) -> None:
643+
**kwargs: _KwargValT) -> None:
644644
if kwargs:
645645

646646
def callback_func(model: ModelT, contents: Any):
@@ -651,9 +651,9 @@ def callback_func(model: ModelT, contents: Any):
651651
super().from_json(data, update=update)
652652

653653

654-
class ListOfParamModelDataset(ParamDataset[ListOfParamModelT, KwargValT],
655-
Generic[ListOfParamModelT, KwargValT]):
656-
def _init(self, super_kwargs: ListOfParamModelSuperKwargsType, **kwargs: KwargValT) -> None:
654+
class ListOfParamModelDataset(ParamDataset[_ListOfParamModelT, _KwargValT],
655+
Generic[_ListOfParamModelT, _KwargValT]):
656+
def _init(self, super_kwargs: ListOfParamModelSuperKwargsType, **kwargs: _KwargValT) -> None:
657657
if kwargs and DATA_KEY in super_kwargs:
658658
super_kwargs[DATA_KEY] = {
659659
key: [DataWithParams(data=_, params=kwargs) for _ in val]

src/omnipy/data/model.py

Lines changed: 29 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
Generic,
1313
get_args,
1414
get_origin,
15+
Hashable,
1516
Optional,
1617
SupportsIndex,
1718
Type,
@@ -46,10 +47,10 @@
4647
RestorableContents)
4748
from omnipy.util.tabulate import tabulate
4849

49-
_KeyT = TypeVar('_KeyT')
50+
_KeyT = TypeVar('_KeyT', bound=Hashable)
5051
_ValT = TypeVar('_ValT')
5152
_IdxT = TypeVar('_IdxT', bound=SupportsIndex)
52-
RootT = TypeVar('RootT', covariant=True, bound=object)
53+
_RootT = TypeVar('_RootT', covariant=True, bound=object)
5354

5455
ROOT_KEY = '__root__'
5556

@@ -132,7 +133,7 @@ def __instancecheck__(self, instance: Any) -> bool:
132133
return super().__instancecheck__(instance)
133134

134135

135-
class Model(GenericModel, Generic[RootT], metaclass=MyModelMetaclass):
136+
class Model(GenericModel, Generic[_RootT], metaclass=MyModelMetaclass):
136137
"""
137138
A data model containing a value parsed according to the model.
138139
@@ -168,7 +169,7 @@ class MyNumberList(Model[list[int]]):
168169
See also docs of the Dataset class for more usage examples.
169170
"""
170171

171-
__root__: RootT | None
172+
__root__: _RootT | None
172173

173174
class Config:
174175
arbitrary_types_allowed = True
@@ -179,7 +180,7 @@ class Config:
179180
# json_dumps = orjson_dumps
180181

181182
@classmethod
182-
def _get_bound_if_typevar(cls, model: Type[RootT]) -> RootT:
183+
def _get_bound_if_typevar(cls, model: Type[_RootT]) -> _RootT:
183184
if isinstance(model, TypeVar):
184185
if model.__bound__ is None: # noqa
185186
raise TypeError('The TypeVar "{}" needs to be bound to a '.format(model.__name__)
@@ -189,7 +190,7 @@ def _get_bound_if_typevar(cls, model: Type[RootT]) -> RootT:
189190
return model
190191

191192
@classmethod
192-
def _get_default_value_from_model(cls, model: Type[RootT]) -> RootT: # noqa: C901
193+
def _get_default_value_from_model(cls, model: Type[_RootT]) -> _RootT: # noqa: C901
193194
model = cls._get_bound_if_typevar(model)
194195
origin_type = get_origin(model)
195196
args = get_args(model)
@@ -219,10 +220,10 @@ def _get_default_value_from_model(cls, model: Type[RootT]) -> RootT: # noqa: C9
219220
return origin_type()
220221

221222
@classmethod
222-
def _populate_root_field(cls, model: Type[RootT]) -> None:
223+
def _populate_root_field(cls, model: Type[_RootT]) -> None:
223224
default_val = cls._get_default_value_from_model(model)
224225

225-
def get_default_val() -> RootT:
226+
def get_default_val() -> _RootT:
226227
return default_val
227228

228229
if ROOT_KEY in cls.__config__.fields:
@@ -251,7 +252,7 @@ def _depopulate_root_field(cls):
251252
del cls.__fields__[ROOT_KEY]
252253
del cls.__annotations__[ROOT_KEY]
253254

254-
def __class_getitem__(cls, model: Type[RootT] | TypeVar) -> 'Model[Type[RootT] | TypeVar]':
255+
def __class_getitem__(cls, model: Type[_RootT] | TypeVar) -> 'Model[Type[_RootT] | TypeVar]':
255256
# TODO: change model type to params: Type[Any], tuple[Type[Any], ...]]
256257
# as in GenericModel
257258

@@ -311,20 +312,20 @@ def __init__(
311312
__root__: Any | UndefinedType = Undefined,
312313
**kwargs: Any,
313314
) -> None:
314-
super_kwargs: dict[str, RootT] = {}
315+
super_kwargs: dict[str, _RootT] = {}
315316
num_root_vals = 0
316317

317318
if value is not Undefined:
318-
super_kwargs[ROOT_KEY] = cast(RootT, value)
319+
super_kwargs[ROOT_KEY] = cast(_RootT, value)
319320
num_root_vals += 1
320321

321322
if __root__ is not Undefined:
322-
super_kwargs[ROOT_KEY] = cast(RootT, __root__)
323+
super_kwargs[ROOT_KEY] = cast(_RootT, __root__)
323324
num_root_vals += 1
324325

325326
if kwargs:
326327
if num_root_vals == 0 or not self.is_param_model():
327-
super_kwargs[ROOT_KEY] = cast(RootT, kwargs)
328+
super_kwargs[ROOT_KEY] = cast(_RootT, kwargs)
328329
kwargs = {}
329330
num_root_vals += 1
330331

@@ -399,11 +400,11 @@ def update_forward_refs(cls, **localns: Any) -> None:
399400
def validate_contents(self) -> None:
400401
self._validate_and_set_contents(self.contents)
401402

402-
def _validate_and_set_contents(self, new_contents: RootT) -> None:
403+
def _validate_and_set_contents(self, new_contents: _RootT) -> None:
403404
self.contents = self._validate_contents_from_value(new_contents)
404405
self._take_snapshot_of_validated_contents()
405406

406-
def _validate_contents_from_value(self, value: RootT) -> RootT:
407+
def _validate_contents_from_value(self, value: _RootT) -> _RootT:
407408
if is_model_instance(value):
408409
value = value.to_data()
409410
elif is_pure_pydantic_model(value):
@@ -428,7 +429,7 @@ def _parse_data(cls, data: Any) -> Any:
428429
return data
429430

430431
@root_validator
431-
def _parse_root_object(cls, root_obj: dict[str, RootT]) -> Any: # noqa
432+
def _parse_root_object(cls, root_obj: dict[str, _RootT]) -> Any: # noqa
432433
assert ROOT_KEY in root_obj
433434
value = root_obj[ROOT_KEY]
434435
value = cls._parse_none_value_with_root_type_if_model(value)
@@ -484,11 +485,11 @@ def _parse_with_root_type_if_model(cls, value: Any, root_field: ModelField,
484485
return value
485486

486487
@property
487-
def contents(self) -> RootT:
488+
def contents(self) -> _RootT:
488489
return self.__dict__.get(ROOT_KEY)
489490

490491
@contents.setter
491-
def contents(self, value: RootT) -> None:
492+
def contents(self, value: _RootT) -> None:
492493
super().__setattr__(ROOT_KEY, value)
493494

494495
def dict(self, *args, **kwargs) -> dict[str, dict[Any, Any]]:
@@ -805,34 +806,34 @@ def _is_table():
805806
ParamModelT = TypeVar('ParamModelT', bound='ParamModel')
806807

807808

808-
class DataWithParams(GenericModel, Generic[RootT, KwargValT]):
809-
data: RootT
809+
class DataWithParams(GenericModel, Generic[_RootT, KwargValT]):
810+
data: _RootT
810811
params: dict[str, KwargValT]
811812

812813

813-
class ParamModel(Model[RootT | DataWithParams[RootT, KwargValT]], Generic[RootT, KwargValT]):
814+
class ParamModel(Model[_RootT | DataWithParams[_RootT, KwargValT]], Generic[_RootT, KwargValT]):
814815
def __class_getitem__(
815-
cls, model: tuple[Type[RootT], Type[KwargValT]]) -> 'ParamModel[RootT, KwargValT]':
816+
cls, model: tuple[Type[_RootT], Type[KwargValT]]) -> 'ParamModel[_RootT, KwargValT]':
816817
created_model = super().__class_getitem__(model)
817818
outer_type = created_model._get_root_type(outer=True, with_args=True)
818819
default_val = cls._get_default_value_from_model(outer_type)
819820

820-
def get_default_val() -> RootT | DataWithParams[RootT, KwargValT]:
821+
def get_default_val() -> _RootT | DataWithParams[_RootT, KwargValT]:
821822
return default_val
822823

823824
root_field = created_model._get_root_field()
824825
root_field.default_factory = get_default_val
825826

826827
return created_model
827828

828-
def _init(self, super_kwargs: dict[str, RootT], **kwargs: KwargValT) -> None:
829+
def _init(self, super_kwargs: dict[str, _RootT], **kwargs: KwargValT) -> None:
829830
if kwargs and ROOT_KEY in super_kwargs:
830831
super_kwargs[ROOT_KEY] = cast(
831-
RootT, DataWithParams(data=super_kwargs[ROOT_KEY], params=kwargs))
832+
_RootT, DataWithParams(data=super_kwargs[ROOT_KEY], params=kwargs))
832833

833834
@root_validator
834835
def _parse_root_object(cls, root_obj: dict[str,
835-
RootT | DataWithParams[RootT, KwargValT]]) -> Any:
836+
_RootT | DataWithParams[_RootT, KwargValT]]) -> Any:
836837
assert ROOT_KEY in root_obj
837838
root_val = root_obj[ROOT_KEY]
838839

@@ -848,7 +849,7 @@ def _parse_root_object(cls, root_obj: dict[str,
848849
return {ROOT_KEY: cls._parse_data(data, **params)}
849850

850851
@classmethod
851-
def _parse_data(cls, data: RootT, **params: KwargValT) -> RootT:
852+
def _parse_data(cls, data: _RootT, **params: KwargValT) -> _RootT:
852853
return data
853854

854855
def from_data(self, value: object, **kwargs: KwargValT) -> None:
@@ -861,7 +862,7 @@ def from_json(self, json_contents: str, **kwargs: KwargValT) -> None:
861862
if kwargs:
862863
self._validate_and_set_contents_with_params(self.contents, **kwargs)
863864

864-
def _validate_and_set_contents_with_params(self, contents: RootT, **kwargs: KwargValT):
865+
def _validate_and_set_contents_with_params(self, contents: _RootT, **kwargs: KwargValT):
865866
self._validate_and_set_contents(DataWithParams(data=contents, params=kwargs))
866867

867868

src/omnipy/modules/general/datasets.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1-
from typing import Generic, TypeVar
1+
from typing import Generic, Hashable, TypeVar
22

33
from omnipy.data.dataset import Dataset
44

5-
_KeyT = TypeVar('_KeyT')
65
from .models import NestedFrozenDictsModel, NestedFrozenDictsOrTuplesModel, NestedFrozenTuplesModel
6+
7+
_KeyT = TypeVar('_KeyT', bound=Hashable)
78
_ScT = TypeVar('_ScT')
89

910

src/omnipy/modules/general/tasks.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,9 @@ def import_directory(directory: str,
5353
return dataset
5454

5555

56-
DatasetT = TypeVar('DatasetT', bound=Dataset)
56+
_DatasetT = TypeVar('_DatasetT', bound=Dataset)
5757

5858

5959
@TaskTemplate
60-
def convert_dataset(dataset: Dataset, dataset_cls: type[DatasetT]) -> DatasetT:
60+
def convert_dataset(dataset: Dataset, dataset_cls: type[_DatasetT]) -> _DatasetT:
6161
return dataset_cls(dataset)

src/omnipy/modules/general/typedefs.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
from collections import UserDict
22
from types import MappingProxyType
3-
from typing import Generic, Sequence, TypeVar
3+
from typing import Generic, Hashable, Sequence, TypeVar
44

5-
_KeyT = TypeVar('_KeyT')
5+
_KeyT = TypeVar('_KeyT', bound=Hashable)
66
_ValT = TypeVar('_ValT')
77

88

src/omnipy/modules/json/datasets.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,10 @@
2929
# TODO: call omnipy modules something else than modules, to distinguish from Python modules.
3030
# Perhaps plugins?
3131
#
32-
JsonModelT = TypeVar('JsonModelT', bound=Model)
32+
_JsonModelT = TypeVar('_JsonModelT', bound=Model)
3333

3434

35-
class JsonBaseDataset(Dataset[JsonModelT], Generic[JsonModelT]):
35+
class JsonBaseDataset(Dataset[_JsonModelT], Generic[_JsonModelT]):
3636
""""""
3737
...
3838

src/omnipy/util/decorators.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
11
from contextlib import AbstractContextManager
22
from typing import Any, Callable, ParamSpec, TypeVar
33

4-
DecoratedP = ParamSpec('DecoratedP')
5-
DecoratedR = TypeVar('DecoratedR')
6-
CallbackP = ParamSpec('CallbackP')
4+
_DecoratedP = ParamSpec('_DecoratedP')
5+
_DecoratedR = TypeVar('_DecoratedR')
6+
_CallbackP = ParamSpec('_CallbackP')
77

88

9-
def add_callback_after_call(func: Callable[DecoratedP, DecoratedR],
10-
callback_func: Callable[CallbackP, None],
11-
*cb_args: CallbackP.args,
9+
def add_callback_after_call(func: Callable[_DecoratedP, _DecoratedR],
10+
callback_func: Callable[_CallbackP, None],
11+
*cb_args: _CallbackP.args,
1212
with_context: AbstractContextManager | None = None,
13-
**cb_kwargs: CallbackP.kwargs) -> Callable[DecoratedP, DecoratedR]:
13+
**cb_kwargs: _CallbackP.kwargs) -> Callable[_DecoratedP, _DecoratedR]:
1414
class ValidateAfterCall(AbstractContextManager):
1515
def __enter__(self):
1616
...
@@ -22,7 +22,7 @@ def __exit__(self, exc_type, exc_val, exc_tb):
2222
callback_func(*cb_args, **cb_kwargs)
2323
return ret
2424

25-
def _inner(*args: DecoratedP.args, **kwargs: DecoratedP.kwargs) -> DecoratedR:
25+
def _inner(*args: _DecoratedP.args, **kwargs: _DecoratedP.kwargs) -> _DecoratedR:
2626
if with_context:
2727
with with_context:
2828
with ValidateAfterCall():

0 commit comments

Comments
 (0)