Skip to content

Commit

Permalink
Infer variant extendability from enum type
Browse files Browse the repository at this point in the history
  • Loading branch information
Pocoder committed Feb 2, 2023
1 parent 0615b90 commit de18752
Show file tree
Hide file tree
Showing 8 changed files with 25 additions and 17 deletions.
2 changes: 1 addition & 1 deletion src/client/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class RuleType(ExtendableStrEnum):
APPROVE_ALL_ASSIGNMENTS = 'APPROVE_ALL_ASSIGNMENTS'


class RuleAction(BaseParameters, spec_enum=RuleType, spec_field='type', extend_spec=True):
class RuleAction(BaseParameters, spec_enum=RuleType, spec_field='type'):
"""Base class for all actions in quality controls configurations
"""

Expand Down
2 changes: 1 addition & 1 deletion src/client/collectors.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def _captcha_deprecation_warning(*args, **kwargs):
)


class CollectorConfig(BaseParameters, spec_enum='Type', spec_field='type', extend_spec=True):
class CollectorConfig(BaseParameters, spec_enum='Type', spec_field='type'):
"""Base class for all collectors.
Attributes:
Expand Down
2 changes: 1 addition & 1 deletion src/client/conditions.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ class RuleConditionKey(ExtendableStrEnum):
TOTAL_SUBMITTED_COUNT = 'total_submitted_count'


class RuleCondition(BaseTolokaObject, spec_enum=RuleConditionKey, spec_field='key', extend_spec=True):
class RuleCondition(BaseTolokaObject, spec_enum=RuleConditionKey, spec_field='key'):
operator: Any
value: Any

Expand Down
4 changes: 2 additions & 2 deletions src/client/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ def structure(cls, data):


@inherit_docstrings
class Profile(Condition, spec_value=Condition.Category.PROFILE, spec_field='key', spec_enum='Key', extend_spec=True):
class Profile(Condition, spec_value=Condition.Category.PROFILE, spec_field='key', spec_enum='Key'):
"""A base class for a category of filters that use Toloker's profile.
"""

Expand All @@ -197,7 +197,7 @@ class Key(ExtendableStrEnum):


@inherit_docstrings
class Computed(Condition, spec_value=Condition.Category.COMPUTED, spec_field='key', spec_enum='Key', extend_spec=True):
class Computed(Condition, spec_value=Condition.Category.COMPUTED, spec_field='key', spec_enum='Key'):
"""A base class for a category of filters that use connection and client information.
"""

Expand Down
15 changes: 9 additions & 6 deletions src/client/primitives/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@

class VariantRegistry:

def __init__(self, field: str, enum: Type[E], extendable: bool = False):
def __init__(self, field: str, enum: Type[E], extendable: Optional[bool] = None):
if extendable is None:
extendable = isinstance(enum, ExtendableStrEnumMetaclass)
if extendable and not isinstance(enum, ExtendableStrEnumMetaclass):
raise ValueError('VariantRegistry could be extendable only if spec_enum is extendable.')
self.field: str = field
Expand All @@ -56,13 +58,14 @@ def register(self, type_: type, value: E) -> type:

def generate_subtype(self, type_: type, value: E) -> type:
if not self.extendable:
raise NotImplementedError("Only extendable VariantRegistry can generate subtype")
raise NotImplementedError('Only extendable VariantRegistry can generate subtype')

generated_type_name = '_Generated' + value.value.title() + type_.__name__
BaseTolokaObjectMetaclass(generated_type_name, (type_,), {}, spec_value=value)
logger.error(f'{generated_type_name} class was generated. Probably it is a new functionality on the platform.\n'
'If you want it to be supported by toloka-kit faster '
'you can make feature request here: https://github.com/Toloka/toloka-kit/issues/new/choose.')
logger.info(f'{generated_type_name} class was generated. '
f'Probably it is a new functionality on the platform.\n'
f'If you want it to be supported by toloka-kit faster you can make feature request here:'
f'https://github.com/Toloka/toloka-kit/issues/new/choose.')
return self.registered_classes[value]

def __getitem__(self, value: E) -> type:
Expand Down Expand Up @@ -194,7 +197,7 @@ def __init_subclass__(
spec_enum: Optional[Union[str, Type[E]]] = None,
spec_field: Optional[str] = None,
spec_value=None,
extend_spec: bool = False,
extend_spec: Optional[bool] = None,
):
super().__init_subclass__()
# Completing a variant type
Expand Down
2 changes: 1 addition & 1 deletion src/client/project/field_spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class FieldType(ExtendableStrEnum):
ARRAY_JSON = 'array_json'


class FieldSpec(BaseTolokaObject, spec_enum=FieldType, spec_field='type', extend_spec=True):
class FieldSpec(BaseTolokaObject, spec_enum=FieldType, spec_field='type'):
"""A base class for field specifications used in project's `input_spec` and `output_spec`
for input and response data validation specification respectively. Use subclasses of this
class defined below to define the data type (string, integer, URL, etc.) and specify
Expand Down
2 changes: 1 addition & 1 deletion src/client/project/template_builder/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def structure(cls, data: dict):
return super().structure(data)


class BaseComponent(BaseTemplate, spec_enum=ComponentType, spec_field='type', extend_spec=True):
class BaseComponent(BaseTemplate, spec_enum=ComponentType, spec_field='type'):

@classmethod
def structure(cls, data: dict):
Expand Down
13 changes: 9 additions & 4 deletions tests/utils/test_variant_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
from typing import Any, Optional

import pytest
from toloka.client._converter import converter
from toloka.client.exceptions import SpecClassIdentificationError
from toloka.client.primitives.base import BaseTolokaObject
from toloka.client._converter import converter
from toloka.util._extendable_enum import ExtendableStrEnum


Expand All @@ -14,11 +15,11 @@ class ItemType(ExtendableStrEnum):


@unique
class SetMethod(ExtendableStrEnum):
class SetMethod(Enum):
POP = 'pop'


class MethodCall(BaseTolokaObject, spec_enum=ItemType, spec_field='type', extend_spec=True):
class MethodCall(BaseTolokaObject, spec_enum=ItemType, spec_field='type'):
pass


Expand All @@ -30,7 +31,7 @@ class SetPopMethodCall(SetMethodCall, spec_value=SetMethod.POP):
pass


class ListMethodCall(MethodCall, spec_value=ItemType.LIST, spec_enum='Method', spec_field='method', extend_spec=True):
class ListMethodCall(MethodCall, spec_value=ItemType.LIST, spec_enum='Method', spec_field='method'):

@unique
class Method(ExtendableStrEnum):
Expand Down Expand Up @@ -116,6 +117,10 @@ def test_structure_unknown_variant():
assert converter.unstructure(
method_call_with_unknown_both_levels_variants) == unstructured_with_unknown_both_levels_variants

with pytest.raises(SpecClassIdentificationError):
unstructured_unextendable = {'type': 'set', 'method': 'new_method'}
converter.structure(unstructured_unextendable, MethodCall)


def test_unstructure_variant():
assert {'type': 'set', 'method': 'pop'} == converter.unstructure(SetPopMethodCall())
Expand Down

0 comments on commit de18752

Please sign in to comment.