Use Self typing

This commit is contained in:
Matthias
2023-06-23 18:15:06 +02:00
parent 01dfca80ab
commit 757c6dc5ca
2 changed files with 14 additions and 11 deletions
+6 -4
View File
@@ -6,6 +6,8 @@ import re
from datetime import datetime, timezone from datetime import datetime, timezone
from typing import Optional from typing import Optional
from typing_extensions import Self
from freqtrade.constants import DATETIME_PRINT_FORMAT from freqtrade.constants import DATETIME_PRINT_FORMAT
from freqtrade.exceptions import OperationalException from freqtrade.exceptions import OperationalException
@@ -107,15 +109,15 @@ class TimeRange:
self.startts = int(min_date.timestamp() + timeframe_secs * startup_candles) self.startts = int(min_date.timestamp() + timeframe_secs * startup_candles)
self.starttype = 'date' self.starttype = 'date'
@staticmethod @classmethod
def parse_timerange(text: Optional[str]) -> 'TimeRange': def parse_timerange(cls, text: Optional[str]) -> Self:
""" """
Parse the value of the argument --timerange to determine what is the range desired Parse the value of the argument --timerange to determine what is the range desired
:param text: value from --timerange :param text: value from --timerange
:return: Start and End range period :return: Start and End range period
""" """
if not text: if not text:
return TimeRange(None, None, 0, 0) return cls(None, None, 0, 0)
syntax = [(r'^-(\d{8})$', (None, 'date')), syntax = [(r'^-(\d{8})$', (None, 'date')),
(r'^(\d{8})-$', ('date', None)), (r'^(\d{8})-$', ('date', None)),
(r'^(\d{8})-(\d{8})$', ('date', 'date')), (r'^(\d{8})-(\d{8})$', ('date', 'date')),
@@ -156,5 +158,5 @@ class TimeRange:
if start > stop > 0: if start > stop > 0:
raise OperationalException( raise OperationalException(
f'Start date is after stop date for timerange "{text}"') f'Start date is after stop date for timerange "{text}"')
return TimeRange(stype[0], stype[1], start, stop) return cls(stype[0], stype[1], start, stop)
raise OperationalException(f'Incorrect syntax for timerange "{text}"') raise OperationalException(f'Incorrect syntax for timerange "{text}"')
+8 -7
View File
@@ -10,6 +10,7 @@ from typing import Any, ClassVar, Dict, List, Optional, Sequence, cast
from sqlalchemy import (Enum, Float, ForeignKey, Integer, ScalarResult, Select, String, from sqlalchemy import (Enum, Float, ForeignKey, Integer, ScalarResult, Select, String,
UniqueConstraint, desc, func, select) UniqueConstraint, desc, func, select)
from sqlalchemy.orm import Mapped, lazyload, mapped_column, relationship, validates from sqlalchemy.orm import Mapped, lazyload, mapped_column, relationship, validates
from typing_extensions import Self
from freqtrade.constants import (CUSTOM_TAG_MAX_LENGTH, DATETIME_PRINT_FORMAT, MATH_CLOSE_PREC, from freqtrade.constants import (CUSTOM_TAG_MAX_LENGTH, DATETIME_PRINT_FORMAT, MATH_CLOSE_PREC,
NON_OPEN_EXCHANGE_STATES, BuySell, LongShort) NON_OPEN_EXCHANGE_STATES, BuySell, LongShort)
@@ -246,15 +247,15 @@ class Order(ModelBase):
else: else:
logger.warning(f"Did not find order for {order}.") logger.warning(f"Did not find order for {order}.")
@staticmethod @classmethod
def parse_from_ccxt_object( def parse_from_ccxt_object(
order: Dict[str, Any], pair: str, side: str, cls, order: Dict[str, Any], pair: str, side: str,
amount: Optional[float] = None, price: Optional[float] = None) -> 'Order': amount: Optional[float] = None, price: Optional[float] = None) -> Self:
""" """
Parse an order from a ccxt object and return a new order Object. Parse an order from a ccxt object and return a new order Object.
Optional support for overriding amount and price is only used for test simplification. Optional support for overriding amount and price is only used for test simplification.
""" """
o = Order( o = cls(
order_id=str(order['id']), order_id=str(order['id']),
ft_order_side=side, ft_order_side=side,
ft_pair=pair, ft_pair=pair,
@@ -1641,8 +1642,8 @@ class Trade(ModelBase, LocalTrade):
)).scalar_one() )).scalar_one()
return trading_volume return trading_volume
@staticmethod @classmethod
def from_json(json_str: str) -> 'Trade': def from_json(cls, json_str: str) -> Self:
""" """
Create a Trade instance from a json string. Create a Trade instance from a json string.
@@ -1652,7 +1653,7 @@ class Trade(ModelBase, LocalTrade):
""" """
import rapidjson import rapidjson
data = rapidjson.loads(json_str) data = rapidjson.loads(json_str)
trade = Trade( trade = cls(
id=data["trade_id"], id=data["trade_id"],
pair=data["pair"], pair=data["pair"],
base_currency=data["base_currency"], base_currency=data["base_currency"],