Skip to content

Commit

Permalink
refactor(exception): set all args besides "message" as key args
Browse files Browse the repository at this point in the history
  • Loading branch information
marshallmallows committed Aug 12, 2021
1 parent 40b93e8 commit dacd2ff
Show file tree
Hide file tree
Showing 14 changed files with 103 additions and 127 deletions.
2 changes: 1 addition & 1 deletion tensorbay/client/gas.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,7 @@ def get_dataset(self, name: str, is_fusion: bool = False) -> DatasetClientType:
status = Status(default_branch, commit_id=commit_id)

if is_fusion != type_flag:
raise DatasetTypeError(name, type_flag)
raise DatasetTypeError(dataset_name=name, is_fusion=type_flag)
ReturnType: Type[DatasetClientType] = FusionDatasetClient if is_fusion else DatasetClient
return ReturnType(name, dataset_id, self, status=status, alias=dataset_alias)

Expand Down
6 changes: 4 additions & 2 deletions tensorbay/client/requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ def request( # type: ignore[override] # pylint: disable=signature-differs
logger.error(
"Unexpected status code(%d)!%s", response.status_code, ResponseLogging(response)
)
raise ResponseError(response)
raise ResponseError(response=response)

logger.debug(ResponseLogging(response))
return response
Expand Down Expand Up @@ -267,7 +267,9 @@ def open_api_do(
except ResponseError as error:
response = error.response
error_code = response.json()["code"]
raise ResponseErrorDistributor.get(error_code, ResponseError)(response) from None
raise ResponseErrorDistributor.get(error_code, ResponseError)(
response=response
) from None

def do(self, method: str, url: str, **kwargs: Any) -> Response: # pylint: disable=invalid-name
"""Send a request.
Expand Down
4 changes: 2 additions & 2 deletions tensorbay/client/status.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def check_authority_for_commit(self) -> None:
"""
if self._commit_id is None or self._draft_number is not None:
raise StatusError(self.is_draft)
raise StatusError(is_draft=self.is_draft)

def check_authority_for_draft(self) -> None:
"""Check whether the status is a legal draft.
Expand All @@ -102,7 +102,7 @@ def check_authority_for_draft(self) -> None:
"""
if self._draft_number is None or self._commit_id is not None:
raise StatusError(self.is_draft)
raise StatusError(is_draft=self.is_draft)

def checkout(self, commit_id: Optional[str] = None, draft_number: Optional[int] = None) -> None:
"""Checkout to commit or draft.
Expand Down
194 changes: 84 additions & 110 deletions tensorbay/exception.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,19 @@


class TensorBayException(Exception):
"""This is the base class for TensorBay custom exceptions."""
"""This is the base class for TensorBay custom exceptions.
Arguments:
message: The error message.
"""

def __init__(self, message: Optional[str] = None):
super().__init__()
self._message = message

def __str__(self) -> str:
return self._message if self._message else ""


class ClientError(TensorBayException):
Expand All @@ -51,17 +63,14 @@ class StatusError(ClientError):
"""

def __init__(self, is_draft: Optional[bool] = None, message: Optional[str] = None) -> None:
def __init__(self, message: Optional[str] = None, *, is_draft: Optional[bool] = None) -> None:
super().__init__()
if is_draft is None:
self._message = message
else:
required_status = "commit" if is_draft else "draft"
self._message = f"The status is not {required_status}"

def __str__(self) -> str:
return self._message if self._message else ""


class DatasetTypeError(ClientError):
"""This class defines the exception for incorrect type of the requested dataset.
Expand All @@ -72,47 +81,30 @@ class DatasetTypeError(ClientError):
"""

def __init__(self, dataset_name: str, is_fusion: bool) -> None:
super().__init__()
def __init__(
self,
message: Optional[str] = None,
*,
dataset_name: Optional[str] = None,
is_fusion: Optional[bool] = None,
) -> None:
super().__init__(message)
self._dataset_name = dataset_name
self._is_fusion = is_fusion

def __str__(self) -> str:
return (
f"Dataset '{self._dataset_name}' is {'' if self._is_fusion else 'not '}a fusion dataset"
)
if self._dataset_name and self._is_fusion:
return f"Dataset '{self._dataset_name}' is \
{'' if self._is_fusion else 'not '}a fusion dataset"
return super().__str__()


class FrameError(ClientError):
"""This class defines the exception for incorrect frame id.
Arguments:
message: The error message.
"""

def __init__(self, message: str) -> None:
super().__init__()
self._message = message

def __str__(self) -> str:
return self._message
"""This class defines the exception for incorrect frame id."""


class OperationError(ClientError):
"""This class defines the exception for incorrect operation.
Arguments:
message: The error message.
"""

def __init__(self, message: str) -> None:
super().__init__()
self._message = message

def __str__(self) -> str:
return self._message
"""This class defines the exception for incorrect operation."""


class ResponseError(ClientError):
Expand All @@ -131,18 +123,23 @@ class ResponseError(ClientError):

STATUS_CODE: int

def __init__(self, response: Response) -> None:
super().__init__()
self.response = response
def __init__(
self, message: Optional[str] = None, *, response: Optional[Response] = None
) -> None:
super().__init__(message)
if response:
self.response = response

def __init_subclass__(cls) -> None:
cls._INDENT = " " * len(cls.__name__)

def __str__(self) -> str:
return (
f"Unexpected status code({self.response.status_code})! {self.response.url}!"
f"\n{self._INDENT} {self.response.text}"
)
if hasattr(self, "response"):
return (
f"Unexpected status code({self.response.status_code})! {self.response.url}!"
f"\n{self._INDENT} {self.response.text}"
)
return super().__str__()


class AccessDeniedError(ResponseError):
Expand All @@ -168,27 +165,24 @@ class InvalidParamsError(ResponseError):

def __init__( # pylint: disable=super-init-not-called
self,
response: Optional[Response] = None,
message: Optional[str] = None,
*,
response: Optional[Response] = None,
param_name: Optional[str] = None,
param_value: Optional[str] = None,
) -> None:
if response is not None:
super().__init__(response)
return

super().__init__(message, response=response)
self._param_name = param_name
self._param_value = param_value

def __str__(self) -> str:
if hasattr(self, "response"):
return super().__str__()

messages = [f"Invalid {self._param_name}: {self._param_value}."]
if self._param_name == "path":
messages.append("Remote path should follow linux style.")
if self._param_name and self._param_value:
messages = [f"Invalid {self._param_name}: {self._param_value}."]
if self._param_name == "path":
messages.append("Remote path should follow linux style.")

return f"\n{self._INDENT}".join(messages)
return f"\n{self._INDENT}".join(messages)
return super().__str__()


class NameConflictError(ResponseError):
Expand All @@ -208,23 +202,20 @@ class NameConflictError(ResponseError):

def __init__( # pylint: disable=super-init-not-called
self,
response: Optional[Response] = None,
message: Optional[str] = None,
*,
response: Optional[Response] = None,
resource: Optional[str] = None,
identification: Union[int, str, None] = None,
) -> None:
if response is not None:
super().__init__(response)
return

super().__init__(message, response=response)
self._resource = resource
self._identification = identification

def __str__(self) -> str:
if hasattr(self, "response"):
return super().__str__()

return f"The {self._resource}: {self._identification} already exists."
if self._resource and self._identification:
return f"The {self._resource}: {self._identification} already exists."
return super().__str__()


class RequestParamsMissingError(ResponseError):
Expand All @@ -250,23 +241,20 @@ class ResourceNotExistError(ResponseError):

def __init__( # pylint: disable=super-init-not-called
self,
response: Optional[Response] = None,
message: Optional[str] = None,
*,
response: Optional[Response] = None,
resource: Optional[str] = None,
identification: Union[int, str, None] = None,
) -> None:
if response is not None:
super().__init__(response)
return

super().__init__(message, response=response)
self._resource = resource
self._identification = identification

def __str__(self) -> str:
if hasattr(self, "response"):
return super().__str__()

return f"The {self._resource}: {self._identification} does not exist."
if self._resource and self._identification:
return f"The {self._resource}: {self._identification} does not exist."
return super().__str__()


class ResponseSystemError(ResponseError):
Expand All @@ -293,28 +281,18 @@ class NoFileError(OpenDatasetError):
"""

def __init__(self, pattern: str) -> None:
super().__init__()
def __init__(self, message: Optional[str] = None, *, pattern: Optional[str] = None) -> None:
super().__init__(message)
self._pattern = pattern

def __str__(self) -> str:
return f'No file follows the giving pattern "{self._pattern}"'
if self._pattern:
return f'No file follows the giving pattern "{self._pattern}"'
return super().__str__()


class FileStructureError(OpenDatasetError):
"""This class defines the exception for incorrect file structure in the opendataset directory.
Arguments:
message: The error message.
"""

def __init__(self, message: str) -> None:
super().__init__()
self._message = message

def __str__(self) -> str:
return self._message
"""This class defines the exception for incorrect file structure in opendataset directory."""


class ModuleImportError(OpenDatasetError, ModuleNotFoundError):
Expand All @@ -326,34 +304,30 @@ class ModuleImportError(OpenDatasetError, ModuleNotFoundError):
"""

def __init__(self, module_name: str, package_name: Optional[str] = None) -> None:
super().__init__()
def __init__(
self,
message: Optional[str] = None,
*,
module_name: Optional[str] = None,
package_name: Optional[str] = None,
) -> None:
super().__init__(message)
self._module_name = module_name
self._package_name = package_name if package_name else module_name

def __str__(self) -> str:
return (
f"No module named {self._module_name}."
"\n"
f'\n To install the module, please run: "pip3 install {self._package_name}"'
"\n"
)
if self._module_name:
return (
f"No module named {self._module_name}."
"\n"
f'\n To install the module, please run: "pip3 install {self._package_name}"'
"\n"
)
return super().__str__()


class TBRNError(TensorBayException):
"""This class defines the exception for invalid TBRN.
Arguments:
message: The error message.
"""

def __init__(self, message: str) -> None:
super().__init__()
self._message = message

def __str__(self) -> str:
return self._message
"""This class defines the exception for invalid TBRN."""


ResponseErrorDistributor: Dict[str, Type[ResponseError]] = {
Expand Down
4 changes: 2 additions & 2 deletions tensorbay/opendataset/AnimalPose/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def _get_data_part1(root_path: str, aniamls: Iterable[str]) -> Iterator[Data]:
try:
import xmltodict # pylint: disable=import-outside-toplevel
except ModuleNotFoundError as error:
raise ModuleImportError(error.name) from error # type: ignore[arg-type]
raise ModuleImportError(module_name=error.name) from error

for animal in aniamls:
for image_path in glob(os.path.join(root_path, "keypoint_image_part1", animal, "*.jpg")):
Expand Down Expand Up @@ -145,7 +145,7 @@ def _get_data_part2(root_path: str, aniamls: Iterable[str]) -> Iterator[Data]:
try:
import xmltodict # pylint: disable=import-outside-toplevel
except ModuleNotFoundError as error:
raise ModuleImportError(error.name) from error # type: ignore[arg-type]
raise ModuleImportError(module_name=error.name) from error

for animal in aniamls:
for image_path in glob(os.path.join(root_path, "animalpose_image_part2", animal, "*.jpeg")):
Expand Down
2 changes: 1 addition & 1 deletion tensorbay/opendataset/BSTLD/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def BSTLD(path: str) -> Dataset:
try:
import yaml # pylint: disable=import-outside-toplevel
except ModuleNotFoundError as error:
raise ModuleImportError(error.name, "pyyaml") from error # type: ignore[arg-type]
raise ModuleImportError(module_name=error.name, package_name="pyyaml") from error

root_path = os.path.abspath(os.path.expanduser(path))

Expand Down
2 changes: 1 addition & 1 deletion tensorbay/opendataset/CACD/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ def _get_labels_map(path: str) -> Dict[str, Tuple[str, Dict[str, Any]]]:
try:
from h5py import File # pylint: disable=import-outside-toplevel
except ModuleNotFoundError as error:
raise ModuleImportError(error.name) from error # type: ignore[arg-type]
raise ModuleImportError(module_name=error.name) from error

mat_file = File(path, "r")
celebrity_image_data = mat_file["celebrityImageData"]
Expand Down
Loading

0 comments on commit dacd2ff

Please sign in to comment.