Apply pylint's linting rules to bfxapi/utils/*.py.

This commit is contained in:
Davide Casale
2023-03-06 17:22:00 +01:00
parent ae14a5d0d1
commit 7288d05939
10 changed files with 36 additions and 32 deletions

View File

@@ -7,9 +7,10 @@ ignore=examples
[MESSAGES CONTROL] [MESSAGES CONTROL]
disable= disable=
multiple-imports,
missing-docstring, missing-docstring,
too-few-public-methods, too-few-public-methods,
dangerous-default-value dangerous-default-value,
[FORMAT] [FORMAT]

View File

@@ -6,7 +6,7 @@ from http import HTTPStatus
from ..enums import Error from ..enums import Error
from ..exceptions import ResourceNotFound, RequestParametersError, InvalidAuthenticationCredentials, UnknownGenericError from ..exceptions import ResourceNotFound, RequestParametersError, InvalidAuthenticationCredentials, UnknownGenericError
from ...utils.JSONEncoder import JSONEncoder from ...utils.json_encoder import JSONEncoder
if TYPE_CHECKING: if TYPE_CHECKING:
from requests.sessions import _Params from requests.sessions import _Params

View File

@@ -4,7 +4,7 @@ from dataclasses import dataclass
from .. labeler import _Type, partial, compose from .. labeler import _Type, partial, compose
from .. notification import Notification from .. notification import Notification
from .. utils.JSONEncoder import JSON from ..utils.json_encoder import JSON
#region Type hinting for Rest Public Endpoints #region Type hinting for Rest Public Endpoints

View File

@@ -1,19 +1,20 @@
import re import re
from typing import TypeVar, Callable, Dict, Any, cast from typing import TypeVar, Callable, cast
T = TypeVar("T") T = TypeVar("T")
_to_snake_case: Callable[[str], str] = lambda string: re.sub(r"(?<!^)(?=[A-Z])", "_", string).lower() _to_snake_case: Callable[[str], str] = lambda string: re.sub(r"(?<!^)(?=[A-Z])", "_", string).lower()
_to_camel_case: Callable[[str], str] = lambda string: (components := string.split("_"))[0] + str().join(c.title() for c in components[1:]) _to_camel_case: Callable[[str], str] = lambda string: \
(components := string.split("_"))[0] + str().join(c.title() for c in components[1:])
def _scheme(data: T, adapter: Callable[[str], str]) -> T: def _scheme(data: T, adapter: Callable[[str], str]) -> T:
if isinstance(data, list): if isinstance(data, list):
return cast(T, [ _scheme(sub_data, adapter) for sub_data in data ]) return cast(T, [ _scheme(sub_data, adapter) for sub_data in data ])
elif isinstance(data, dict): if isinstance(data, dict):
return cast(T, { adapter(key): _scheme(value, adapter) for key, value in data.items() }) return cast(T, { adapter(key): _scheme(value, adapter) for key, value in data.items() })
else: return data return data
def to_snake_case_keys(dictionary: T) -> T: def to_snake_case_keys(dictionary: T) -> T:
return _scheme(dictionary, _to_snake_case) return _scheme(dictionary, _to_snake_case)

View File

@@ -7,23 +7,25 @@ from typing import Type, List, Dict, Union, Any
JSON = Union[Dict[str, "JSON"], List["JSON"], bool, int, float, str, Type[None]] JSON = Union[Dict[str, "JSON"], List["JSON"], bool, int, float, str, Type[None]]
def _strip(dictionary: Dict) -> Dict: def _strip(dictionary: Dict) -> Dict:
return { key: value for key, value in dictionary.items() if value != None} return { key: value for key, value in dictionary.items() if value is not None }
def _convert_float_to_str(data: JSON) -> JSON: def _convert_float_to_str(data: JSON) -> JSON:
if isinstance(data, float): if isinstance(data, float):
return format(Decimal(repr(data)), "f") return format(Decimal(repr(data)), "f")
elif isinstance(data, list): if isinstance(data, list):
return [ _convert_float_to_str(sub_data) for sub_data in data ] return [ _convert_float_to_str(sub_data) for sub_data in data ]
elif isinstance(data, dict): if isinstance(data, dict):
return _strip({ key: _convert_float_to_str(value) for key, value in data.items() }) return _strip({ key: _convert_float_to_str(value) for key, value in data.items() })
else: return data return data
class JSONEncoder(json.JSONEncoder): class JSONEncoder(json.JSONEncoder):
def encode(self, obj: JSON) -> str: def encode(self, o: JSON) -> str:
return json.JSONEncoder.encode(self, _convert_float_to_str(obj)) return json.JSONEncoder.encode(self, _convert_float_to_str(o))
def default(self, obj: Any) -> Any: def default(self, o: Any) -> Any:
if isinstance(obj, Decimal): return format(obj, "f") if isinstance(o, Decimal):
elif isinstance(obj, datetime): return str(obj) return format(o, "f")
if isinstance(o, datetime):
return str(o)
return json.JSONEncoder.default(self, obj) return json.JSONEncoder.default(self, o)

View File

@@ -33,10 +33,10 @@ class ColorLogger(logging.Logger):
logging.Logger.__init__(self, name, level) logging.Logger.__init__(self, name, level)
colored_formatter = _ColorFormatter(self.FORMAT, use_color=True) colored_formatter = _ColorFormatter(self.FORMAT, use_color=True)
console = logging.StreamHandler(stream=sys.stderr) handler = logging.StreamHandler(stream=sys.stderr)
console.setFormatter(fmt=colored_formatter) handler.setFormatter(fmt=colored_formatter)
self.addHandler(hdlr=console) self.addHandler(hdlr=handler)
class FileLogger(logging.Logger): class FileLogger(logging.Logger):
FORMAT = "[%(name)s] [%(levelname)s] [%(asctime)s] %(message)s" FORMAT = "[%(name)s] [%(levelname)s] [%(asctime)s] %(message)s"
@@ -45,7 +45,7 @@ class FileLogger(logging.Logger):
logging.Logger.__init__(self, name, level) logging.Logger.__init__(self, name, level)
formatter = logging.Formatter(self.FORMAT) formatter = logging.Formatter(self.FORMAT)
fh = logging.FileHandler(filename=filename) handler = logging.FileHandler(filename=filename)
fh.setFormatter(fmt=formatter) handler.setFormatter(fmt=formatter)
self.addHandler(hdlr=fh) self.addHandler(hdlr=handler)

View File

@@ -14,7 +14,7 @@ from .bfx_websocket_inputs import BfxWebsocketInputs
from ..handlers import PublicChannelsHandler, AuthenticatedChannelsHandler from ..handlers import PublicChannelsHandler, AuthenticatedChannelsHandler
from ..exceptions import WebsocketAuthenticationRequired, InvalidAuthenticationCredentials, EventNotSupported, OutdatedClientVersion from ..exceptions import WebsocketAuthenticationRequired, InvalidAuthenticationCredentials, EventNotSupported, OutdatedClientVersion
from ...utils.JSONEncoder import JSONEncoder from ...utils.json_encoder import JSONEncoder
from ...utils.logger import ColorLogger, FileLogger from ...utils.logger import ColorLogger, FileLogger

View File

@@ -3,7 +3,7 @@ from datetime import datetime
from typing import Union, Optional, List, Tuple from typing import Union, Optional, List, Tuple
from .. enums import OrderType, FundingOfferType from .. enums import OrderType, FundingOfferType
from ... utils.JSONEncoder import JSON from ...utils.json_encoder import JSON
class BfxWebsocketInputs(object): class BfxWebsocketInputs(object):
def __init__(self, handle_websocket_input): def __init__(self, handle_websocket_input):

View File

@@ -4,7 +4,7 @@ from dataclasses import dataclass
from .. labeler import _Type from .. labeler import _Type
from .. notification import Notification from .. notification import Notification
from .. utils.JSONEncoder import JSON from ..utils.json_encoder import JSON
#region Type hinting for Websocket Public Channels #region Type hinting for Websocket Public Channels