Add safe_value_fallback function
This commit is contained in:
parent
346e09fed1
commit
cbf5bf6735
@ -134,6 +134,21 @@ def round_dict(d, n):
|
||||
return {k: (round(v, n) if isinstance(v, float) else v) for k, v in d.items()}
|
||||
|
||||
|
||||
def safe_value_fallback(dict1: dict, dict2: dict, key1: str, key2: str, default_value=None):
|
||||
"""
|
||||
Search a value in dict1, return this if it's not None.
|
||||
Fall back to dict2 - return key2 from dict2 if it's not None.
|
||||
Else falls back to None.
|
||||
|
||||
"""
|
||||
if key1 in dict1 and dict1[key1] is not None:
|
||||
return dict1[key1]
|
||||
else:
|
||||
if key2 in dict2 and dict2[key2] is not None:
|
||||
return dict2[key2]
|
||||
return default_value
|
||||
|
||||
|
||||
def plural(num: float, singular: str, plural: str = None) -> str:
|
||||
return singular if (num == 1 or num == -1) else plural or singular + 's'
|
||||
|
||||
|
@ -9,7 +9,7 @@ import pytest
|
||||
from freqtrade.data.converter import ohlcv_to_dataframe
|
||||
from freqtrade.misc import (datesarray_to_datetimearray, file_dump_json,
|
||||
file_load_json, format_ms_time, pair_to_filename,
|
||||
plural, shorten_date)
|
||||
plural, safe_value_fallback, shorten_date)
|
||||
|
||||
|
||||
def test_shorten_date() -> None:
|
||||
@ -93,6 +93,19 @@ def test_format_ms_time() -> None:
|
||||
assert format_ms_time(date_in_epoch_ms) == res.astimezone(None).strftime('%Y-%m-%dT%H:%M:%S')
|
||||
|
||||
|
||||
def test_safe_value_fallback():
|
||||
dict1 = {'keya': None, 'keyb': 2, 'keyc': 5}
|
||||
dict2 = {'keya': 20, 'keyb': None, 'keyc': 6}
|
||||
assert safe_value_fallback(dict1, dict2, 'keya', 'keya') == 20
|
||||
assert safe_value_fallback(dict2, dict1, 'keya', 'keya') == 20
|
||||
|
||||
assert safe_value_fallback(dict1, dict2, 'keyb', 'keyb') == 2
|
||||
assert safe_value_fallback(dict2, dict1, 'keyb', 'keyb') == 2
|
||||
|
||||
assert safe_value_fallback(dict1, dict2, 'keyc', 'keyc') == 5
|
||||
assert safe_value_fallback(dict2, dict1, 'keyc', 'keyc') == 6
|
||||
|
||||
|
||||
def test_plural() -> None:
|
||||
assert plural(0, "page") == "pages"
|
||||
assert plural(0.0, "page") == "pages"
|
||||
|
Loading…
Reference in New Issue
Block a user