Skip to content

Linting base extension #17

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Mar 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,38 +3,38 @@

from .meta import (
Datum,
_ConverterMeta,
_BaseConverter,
InConverter,
OutConverter,
_BaseConverter,
_ConverterMeta,
get_binding_registry,
)
from .sdkType import SdkType
from .web import (
WebServer,
WebApp,
HttpV2FeatureChecker,
ModuleTrackerMeta,
RequestTrackerMeta,
ResponseLabels,
ResponseTrackerMeta,
HttpV2FeatureChecker,
ResponseLabels
WebApp,
WebServer,
)

__all__ = [
'Datum',
'_ConverterMeta',
'_BaseConverter',
'InConverter',
'OutConverter',
'SdkType',
'get_binding_registry',
'ModuleTrackerMeta',
'RequestTrackerMeta',
'ResponseTrackerMeta',
'HttpV2FeatureChecker',
'ResponseLabels',
'WebServer',
'WebApp'
"Datum",
"_ConverterMeta",
"_BaseConverter",
"InConverter",
"OutConverter",
"SdkType",
"get_binding_registry",
"ModuleTrackerMeta",
"RequestTrackerMeta",
"ResponseTrackerMeta",
"HttpV2FeatureChecker",
"ResponseLabels",
"WebServer",
"WebApp",
]

__version__ = "1.0.0a2"
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,9 @@
import abc
import inspect
import json
from typing import Any, Dict, List, Mapping, Optional, Tuple, Union

from . import utils
from . import sdkType

from typing import Any, Dict, List, Optional, Mapping, Union, Tuple
from . import sdkType, utils


class Datum:
Expand All @@ -20,17 +18,17 @@ def __init__(self, value: Any, type: Optional[str]):
def python_value(self) -> Any:
if self.value is None or self.type is None:
return None
elif self.type in ('bytes', 'string', 'int', 'double'):
elif self.type in ("bytes", "string", "int", "double"):
return self.value
elif self.type == 'json':
elif self.type == "json":
return json.loads(self.value)
elif self.type == 'collection_string':
elif self.type == "collection_string":
return [v for v in self.value.string]
elif self.type == 'collection_bytes':
elif self.type == "collection_bytes":
return [v for v in self.value.bytes]
elif self.type == 'collection_double':
elif self.type == "collection_double":
return [v for v in self.value.double]
elif self.type == 'collection_sint64':
elif self.type == "collection_sint64":
return [v for v in self.value.sint64]
else:
return self.value
Expand All @@ -51,27 +49,28 @@ def __hash__(self):
def __repr__(self):
val_repr = repr(self.value)
if len(val_repr) > 10:
val_repr = val_repr[:10] + '...'
return '<Datum {} {}>'.format(self.type, val_repr)
val_repr = val_repr[:10] + "..."
return "<Datum {} {}>".format(self.type, val_repr)


class _ConverterMeta(abc.ABCMeta):

_bindings: Dict[str, type] = {}

def __new__(mcls, name, bases, dct, *,
binding: Optional[str],
trigger: Optional[str] = None):
def __new__(
mcls, name, bases, dct, *, binding: Optional[str], trigger: Optional[str] = None
):
cls = super().__new__(mcls, name, bases, dct)
cls._trigger = trigger # type: ignore
if binding is None:
return cls

if binding in mcls._bindings:
raise RuntimeError(
f'cannot register a converter for {binding!r} binding: '
f'another converter for this binding has already been '
f'registered')
f"cannot register a converter for {binding!r} binding: "
f"another converter for this binding has already been "
f"registered"
)

mcls._bindings[binding] = cls
if trigger is not None:
Expand Down Expand Up @@ -101,51 +100,59 @@ class _BaseConverter(metaclass=_ConverterMeta, binding=None):

@classmethod
def _decode_typed_data(
cls, data: Datum, *,
python_type: Union[type, Tuple[type, ...]],
context: str = 'data') -> Any:
cls,
data: Datum,
*,
python_type: Union[type, Tuple[type, ...]],
context: str = "data",
) -> Any:
if data is None:
return None

data_type = data.type
if data_type == 'model_binding_data':
if data_type == "model_binding_data":
result = data.value
elif data_type is None:
return None
else:
raise ValueError(
f'unsupported type of {context}: {data_type}')
raise ValueError(f"unsupported type of {context}: {data_type}")

if not isinstance(result, python_type):
if isinstance(python_type, (tuple, list, dict)):
raise ValueError(
f'unexpected value type in {context}: '
f'{type(result).__name__}, expected one of: '
f'{", ".join(t.__name__ for t in python_type)}')
f"unexpected value type in {context}: "
f"{type(result).__name__}, expected one of: "
f'{", ".join(t.__name__ for t in python_type)}'
)
else:
try:
# Try coercing into the requested type
result = python_type(result)
except (TypeError, ValueError) as e:
raise ValueError(
f'cannot convert value of {context} into '
f'{python_type.__name__}: {e}') from None
f"cannot convert value of {context} into "
f"{python_type.__name__}: {e}"
) from None

return result

@classmethod
def _decode_trigger_metadata_field(
cls, trigger_metadata: Mapping[str, Datum],
field: str, *,
python_type: Union[type, Tuple[type, ...]]) \
-> Any:
cls,
trigger_metadata: Mapping[str, Datum],
field: str,
*,
python_type: Union[type, Tuple[type, ...]],
) -> Any:
data = trigger_metadata.get(field)
if data is None:
return None
else:
return cls._decode_typed_data(
data, python_type=python_type,
context=f'field {field!r} in trigger metadata')
data,
python_type=python_type,
context=f"field {field!r} in trigger metadata",
)


class InConverter(_BaseConverter, binding=None):
Expand Down Expand Up @@ -175,8 +182,7 @@ def check_output_type_annotation(cls, pytype: type) -> bool:

@classmethod
@abc.abstractmethod
def encode(cls, obj: Any, *,
expected_type: Optional[type]) -> Optional[Datum]:
def encode(cls, obj: Any, *, expected_type: Optional[type]) -> Optional[Datum]:
raise NotImplementedError


Expand Down
Loading