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]
disable=
multiple-imports,
missing-docstring,
too-few-public-methods,
dangerous-default-value
dangerous-default-value,
[FORMAT]

View File

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

View File

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

View File

@@ -1 +1 @@
NAME = "utils"
NAME = "utils"

View File

@@ -1,22 +1,23 @@
import re
from typing import TypeVar, Callable, Dict, Any, cast
from typing import TypeVar, Callable, cast
T = TypeVar("T")
_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:
if isinstance(data, list):
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() })
else: return data
return data
def to_snake_case_keys(dictionary: T) -> T:
return _scheme(dictionary, _to_snake_case)
def to_camel_case_keys(dictionary: T) -> T:
return _scheme(dictionary, _to_camel_case)
return _scheme(dictionary, _to_camel_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]]
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:
if isinstance(data, float):
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 ]
elif isinstance(data, dict):
if isinstance(data, dict):
return _strip({ key: _convert_float_to_str(value) for key, value in data.items() })
else: return data
return data
class JSONEncoder(json.JSONEncoder):
def encode(self, obj: JSON) -> str:
return json.JSONEncoder.encode(self, _convert_float_to_str(obj))
def encode(self, o: JSON) -> str:
return json.JSONEncoder.encode(self, _convert_float_to_str(o))
def default(self, obj: Any) -> Any:
if isinstance(obj, Decimal): return format(obj, "f")
elif isinstance(obj, datetime): return str(obj)
def default(self, o: Any) -> Any:
if isinstance(o, Decimal):
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

@@ -28,24 +28,24 @@ class _ColorFormatter(logging.Formatter):
class ColorLogger(logging.Logger):
FORMAT = "[%(name)s] [%(levelname)s] [%(asctime)s] %(message)s"
def __init__(self, name, level):
logging.Logger.__init__(self, name, level)
logging.Logger.__init__(self, name, level)
colored_formatter = _ColorFormatter(self.FORMAT, use_color=True)
console = logging.StreamHandler(stream=sys.stderr)
console.setFormatter(fmt=colored_formatter)
handler = logging.StreamHandler(stream=sys.stderr)
handler.setFormatter(fmt=colored_formatter)
self.addHandler(hdlr=console)
self.addHandler(hdlr=handler)
class FileLogger(logging.Logger):
FORMAT = "[%(name)s] [%(levelname)s] [%(asctime)s] %(message)s"
def __init__(self, name, level, filename):
logging.Logger.__init__(self, name, level)
logging.Logger.__init__(self, name, level)
formatter = logging.Formatter(self.FORMAT)
fh = logging.FileHandler(filename=filename)
fh.setFormatter(fmt=formatter)
handler = logging.FileHandler(filename=filename)
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 ..exceptions import WebsocketAuthenticationRequired, InvalidAuthenticationCredentials, EventNotSupported, OutdatedClientVersion
from ...utils.JSONEncoder import JSONEncoder
from ...utils.json_encoder import JSONEncoder
from ...utils.logger import ColorLogger, FileLogger

View File

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

View File

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