Fix type hinting in module bfxapi._utils.json_encoder.

This commit is contained in:
Davide Casale
2023-10-08 19:54:50 +02:00
parent 5ae576e36a
commit 9872adf60f
4 changed files with 27 additions and 29 deletions

View File

@@ -2,17 +2,21 @@ import json
from decimal import Decimal from decimal import Decimal
from typing import List, Dict, Union from typing import \
Union, List, Dict, \
Any
JSON = Union[Dict[str, "JSON"], List["JSON"], bool, int, float, str, None] _ExtJSON = Union[Dict[str, "_ExtJSON"], List["_ExtJSON"], \
_CustomJSON = Union[Dict[str, "_CustomJSON"], List["_CustomJSON"], \
bool, int, float, str, Decimal, None] bool, int, float, str, Decimal, None]
def _strip(dictionary: Dict) -> Dict: _StrictJSON = Union[Dict[str, "_StrictJSON"], List["_StrictJSON"], \
return { key: value for key, value in dictionary.items() if value is not None } int, str, None]
def _convert_data_to_json(data: _CustomJSON) -> JSON: def _clear(dictionary: Dict[str, Any]) -> Dict[str, Any]:
return { key: value for key, value in dictionary.items() \
if value is not None }
def _adapter(data: _ExtJSON) -> _StrictJSON:
if isinstance(data, bool): if isinstance(data, bool):
return int(data) return int(data)
if isinstance(data, float): if isinstance(data, float):
@@ -21,12 +25,12 @@ def _convert_data_to_json(data: _CustomJSON) -> JSON:
return format(data, "f") return format(data, "f")
if isinstance(data, list): if isinstance(data, list):
return [ _convert_data_to_json(sub_data) for sub_data in data ] return [ _adapter(sub_data) for sub_data in data ]
if isinstance(data, dict): if isinstance(data, dict):
return _strip({ key: _convert_data_to_json(value) for key, value in data.items() }) return _clear({ key: _adapter(value) for key, value in data.items() })
return data return data
class JSONEncoder(json.JSONEncoder): class JSONEncoder(json.JSONEncoder):
def encode(self, o: _CustomJSON) -> str: def encode(self, o: _ExtJSON) -> str:
return json.JSONEncoder.encode(self, _convert_data_to_json(o)) return super().encode(_adapter(o))

View File

@@ -1,4 +1,4 @@
from typing import Dict, List, Tuple, Union, Literal, Optional from typing import Dict, List, Tuple, Union, Literal, Optional, Any
from decimal import Decimal from decimal import Decimal
@@ -22,8 +22,6 @@ from ...types import serializers
from ...types.serializers import _Notification from ...types.serializers import _Notification
from ..._utils.json_encoder import JSON
class RestAuthEndpoints(Middleware): class RestAuthEndpoints(Middleware):
def get_user_info(self) -> UserInfo: def get_user_info(self) -> UserInfo:
return serializers.UserInfo \ return serializers.UserInfo \
@@ -77,7 +75,7 @@ class RestAuthEndpoints(Middleware):
cid: Optional[int] = None, cid: Optional[int] = None,
flags: Optional[int] = 0, flags: Optional[int] = 0,
tif: Optional[str] = None, tif: Optional[str] = None,
meta: Optional[JSON] = None) -> Notification[Order]: meta: Optional[Dict[str, Any]] = None) -> Notification[Order]:
body = { body = {
"type": type, "symbol": symbol, "amount": amount, "type": type, "symbol": symbol, "amount": amount,
"price": price, "lev": lev, "price_trailing": price_trailing, "price": price, "lev": lev, "price_trailing": price_trailing,

View File

@@ -5,8 +5,6 @@ from dataclasses import dataclass
from .labeler import _Type, partial, compose from .labeler import _Type, partial, compose
from .._utils.json_encoder import JSON
#region Dataclass definitions for types of public use #region Dataclass definitions for types of public use
@dataclass @dataclass
@@ -172,7 +170,7 @@ class PulseMessage(_Type):
comments_disabled: int comments_disabled: int
tags: List[str] tags: List[str]
attachments: List[str] attachments: List[str]
meta: List[JSON] meta: List[Dict[str, Any]]
likes: int likes: int
profile: PulseProfile profile: PulseProfile
comments: int comments: int
@@ -231,7 +229,7 @@ class LoginHistory(_Type):
id: int id: int
time: int time: int
ip: str ip: str
extra_info: JSON extra_info: Dict[str, Any]
@dataclass @dataclass
class BalanceAvailable(_Type): class BalanceAvailable(_Type):
@@ -260,7 +258,7 @@ class Order(_Type):
hidden: int hidden: int
placed_id: int placed_id: int
routing: str routing: str
meta: JSON meta: Dict[str, Any]
@dataclass @dataclass
class Position(_Type): class Position(_Type):
@@ -280,7 +278,7 @@ class Position(_Type):
type: int type: int
collateral: float collateral: float
collateral_min: float collateral_min: float
meta: JSON meta: Dict[str, Any]
@dataclass @dataclass
class Trade(_Type): class Trade(_Type):
@@ -409,7 +407,7 @@ class Wallet(_Type):
unsettled_interest: float unsettled_interest: float
available_balance: float available_balance: float
last_change: str last_change: str
trade_details: JSON trade_details: Dict[str, Any]
@dataclass @dataclass
class Transfer(_Type): class Transfer(_Type):
@@ -486,7 +484,7 @@ class PositionClaim(_Type):
pos_type: int pos_type: int
collateral: str collateral: str
min_collateral: str min_collateral: str
meta: JSON meta: Dict[str, Any]
@dataclass @dataclass
class PositionIncreaseInfo(_Type): class PositionIncreaseInfo(_Type):
@@ -547,7 +545,7 @@ class PositionAudit(_Type):
type: int type: int
collateral: float collateral: float
collateral_min: float collateral_min: float
meta: JSON meta: Dict[str, Any]
@dataclass @dataclass
class DerivativePositionCollateral(_Type): class DerivativePositionCollateral(_Type):
@@ -618,7 +616,7 @@ class InvoiceSubmission(_Type):
pay_currency: str pay_currency: str
pool_currency: str pool_currency: str
address: str address: str
ext: JSON ext: Dict[str, Any]
@compose(dataclass, partial) @compose(dataclass, partial)
class Payment: class Payment:

View File

@@ -1,12 +1,10 @@
from typing import TYPE_CHECKING, Callable, Awaitable, \ from typing import TYPE_CHECKING, Callable, Awaitable, \
Tuple, List, Union, Optional, Any Tuple, List, Dict, Union, Optional, Any
if TYPE_CHECKING: if TYPE_CHECKING:
from bfxapi.enums import \ from bfxapi.enums import \
OrderType, FundingOfferType OrderType, FundingOfferType
from bfxapi._utils.json_encoder import JSON
from decimal import Decimal from decimal import Decimal
class BfxWebSocketInputs: class BfxWebSocketInputs:
@@ -27,7 +25,7 @@ class BfxWebSocketInputs:
cid: Optional[int] = None, cid: Optional[int] = None,
flags: Optional[int] = 0, flags: Optional[int] = 0,
tif: Optional[str] = None, tif: Optional[str] = None,
meta: Optional["JSON"] = None) -> None: meta: Optional[Dict[str, Any]] = None) -> None:
await self.__handle_websocket_input("on", { await self.__handle_websocket_input("on", {
"type": type, "symbol": symbol, "amount": amount, "type": type, "symbol": symbol, "amount": amount,
"price": price, "lev": lev, "price_trailing": price_trailing, "price": price, "lev": lev, "price_trailing": price_trailing,