use Path.open() instead of open

This commit is contained in:
Matthias 2023-02-25 17:08:02 +01:00
parent c8a4a773ee
commit d014e4590e
10 changed files with 17 additions and 17 deletions

View File

@ -58,7 +58,7 @@ def load_config_file(path: str) -> Dict[str, Any]:
""" """
try: try:
# Read config from stdin if requested in the options # Read config from stdin if requested in the options
with open(path) if path != '-' else sys.stdin as file: with Path(path).open() if path != '-' else sys.stdin as file:
config = rapidjson.load(file, parse_mode=CONFIG_PARSE_MODE) config = rapidjson.load(file, parse_mode=CONFIG_PARSE_MODE)
except FileNotFoundError: except FileNotFoundError:
raise OperationalException( raise OperationalException(

View File

@ -24,9 +24,9 @@ def _load_signal_candles(backtest_dir: Path):
scpf = Path(backtest_dir.parent / f"{backtest_dir.stem}_signals.pkl") scpf = Path(backtest_dir.parent / f"{backtest_dir.stem}_signals.pkl")
try: try:
scp = open(scpf, "rb") with scpf.open("rb") as scp:
signal_candles = joblib.load(scp) signal_candles = joblib.load(scp)
logger.info(f"Loaded signal candles: {str(scpf)}") logger.info(f"Loaded signal candles: {str(scpf)}")
except Exception as e: except Exception as e:
logger.error("Cannot load signal candles from pickled results: ", e) logger.error("Cannot load signal candles from pickled results: ", e)

View File

@ -195,7 +195,7 @@ class Binance(Exchange):
leverage_tiers_path = ( leverage_tiers_path = (
Path(__file__).parent / 'binance_leverage_tiers.json' Path(__file__).parent / 'binance_leverage_tiers.json'
) )
with open(leverage_tiers_path) as json_file: with leverage_tiers_path.open() as json_file:
return json_load(json_file) return json_load(json_file)
else: else:
try: try:

View File

@ -81,7 +81,7 @@ def file_dump_json(filename: Path, data: Any, is_zip: bool = False, log: bool =
else: else:
if log: if log:
logger.info(f'dumping json to "{filename}"') logger.info(f'dumping json to "{filename}"')
with open(filename, 'w') as fp: with filename.open('w') as fp:
rapidjson.dump(data, fp, default=str, number_mode=rapidjson.NM_NATIVE) rapidjson.dump(data, fp, default=str, number_mode=rapidjson.NM_NATIVE)
logger.debug(f'done json to "{filename}"') logger.debug(f'done json to "{filename}"')
@ -98,7 +98,7 @@ def file_dump_joblib(filename: Path, data: Any, log: bool = True) -> None:
if log: if log:
logger.info(f'dumping joblib to "{filename}"') logger.info(f'dumping joblib to "{filename}"')
with open(filename, 'wb') as fp: with filename.open('wb') as fp:
joblib.dump(data, fp) joblib.dump(data, fp)
logger.debug(f'done joblib dump to "{filename}"') logger.debug(f'done joblib dump to "{filename}"')
@ -112,7 +112,7 @@ def json_load(datafile: IO) -> Any:
return rapidjson.load(datafile, number_mode=rapidjson.NM_NATIVE) return rapidjson.load(datafile, number_mode=rapidjson.NM_NATIVE)
def file_load_json(file): def file_load_json(file: Path):
if file.suffix != ".gz": if file.suffix != ".gz":
gzipfile = file.with_suffix(file.suffix + '.gz') gzipfile = file.with_suffix(file.suffix + '.gz')
@ -125,7 +125,7 @@ def file_load_json(file):
pairdata = json_load(datafile) pairdata = json_load(datafile)
elif file.is_file(): elif file.is_file():
logger.debug(f"Loading historical data from file {file}") logger.debug(f"Loading historical data from file {file}")
with open(file) as datafile: with file.open() as datafile:
pairdata = json_load(datafile) pairdata = json_load(datafile)
else: else:
return None return None

View File

@ -29,7 +29,7 @@ def get_strategy_run_id(strategy) -> str:
# Include _ft_params_from_file - so changing parameter files cause cache eviction # Include _ft_params_from_file - so changing parameter files cause cache eviction
digest.update(rapidjson.dumps( digest.update(rapidjson.dumps(
strategy._ft_params_from_file, default=str, number_mode=rapidjson.NM_NAN).encode('utf-8')) strategy._ft_params_from_file, default=str, number_mode=rapidjson.NM_NAN).encode('utf-8'))
with open(strategy.__file__, 'rb') as fp: with Path(strategy.__file__).open('rb') as fp:
digest.update(fp.read()) digest.update(fp.read())
return digest.hexdigest().lower() return digest.hexdigest().lower()

View File

@ -157,7 +157,7 @@ class RemotePairList(IPairList):
file_path = Path(filename) file_path = Path(filename)
if file_path.exists(): if file_path.exists():
with open(filename) as json_file: with file_path.open() as json_file:
# Load the JSON data into a dictionary # Load the JSON data into a dictionary
jsonparse = json.load(json_file) jsonparse = json.load(json_file)

View File

@ -191,7 +191,7 @@ def test_load_cached_data_for_updating(mocker, testdatadir) -> None:
test_data = None test_data = None
test_filename = testdatadir.joinpath('UNITTEST_BTC-1m.json') test_filename = testdatadir.joinpath('UNITTEST_BTC-1m.json')
with open(test_filename, "rt") as file: with test_filename.open("rt") as file:
test_data = json.load(file) test_data = json.load(file)
test_data_df = ohlcv_to_dataframe(test_data, '1m', 'UNITTEST/BTC', test_data_df = ohlcv_to_dataframe(test_data, '1m', 'UNITTEST/BTC',

View File

@ -255,7 +255,7 @@ def test_write_read_backtest_candles(tmpdir):
# test directory exporting # test directory exporting
stored_file = store_backtest_signal_candles(Path(tmpdir), candle_dict, '2022_01_01_15_05_13') stored_file = store_backtest_signal_candles(Path(tmpdir), candle_dict, '2022_01_01_15_05_13')
scp = open(stored_file, "rb") scp = stored_file.open("rb")
pickled_signal_candles = joblib.load(scp) pickled_signal_candles = joblib.load(scp)
scp.close() scp.close()
@ -269,7 +269,7 @@ def test_write_read_backtest_candles(tmpdir):
# test file exporting # test file exporting
filename = Path(tmpdir / 'testresult') filename = Path(tmpdir / 'testresult')
stored_file = store_backtest_signal_candles(filename, candle_dict, '2022_01_01_15_05_13') stored_file = store_backtest_signal_candles(filename, candle_dict, '2022_01_01_15_05_13')
scp = open(stored_file, "rb") scp = stored_file.open("rb")
pickled_signal_candles = joblib.load(scp) pickled_signal_candles = joblib.load(scp)
scp.close() scp.close()

View File

@ -59,7 +59,7 @@ def test_load_config_incorrect_stake_amount(default_conf) -> None:
def test_load_config_file(default_conf, mocker, caplog) -> None: def test_load_config_file(default_conf, mocker, caplog) -> None:
del default_conf['user_data_dir'] del default_conf['user_data_dir']
default_conf['datadir'] = str(default_conf['datadir']) default_conf['datadir'] = str(default_conf['datadir'])
file_mock = mocker.patch('freqtrade.configuration.load_config.open', mocker.mock_open( file_mock = mocker.patch('freqtrade.configuration.load_config.Path.open', mocker.mock_open(
read_data=json.dumps(default_conf) read_data=json.dumps(default_conf)
)) ))
@ -272,7 +272,7 @@ def test_load_config_max_open_trades_minus_one(default_conf, mocker, caplog) ->
def test_load_config_file_exception(mocker) -> None: def test_load_config_file_exception(mocker) -> None:
mocker.patch( mocker.patch(
'freqtrade.configuration.configuration.open', 'freqtrade.configuration.configuration.Path.open',
MagicMock(side_effect=FileNotFoundError('File not found')) MagicMock(side_effect=FileNotFoundError('File not found'))
) )

View File

@ -46,7 +46,7 @@ def test_shorten_date() -> None:
def test_file_dump_json(mocker) -> None: def test_file_dump_json(mocker) -> None:
file_open = mocker.patch('freqtrade.misc.open', MagicMock()) file_open = mocker.patch('freqtrade.misc.Path.open', MagicMock())
json_dump = mocker.patch('rapidjson.dump', MagicMock()) json_dump = mocker.patch('rapidjson.dump', MagicMock())
file_dump_json(Path('somefile'), [1, 2, 3]) file_dump_json(Path('somefile'), [1, 2, 3])
assert file_open.call_count == 1 assert file_open.call_count == 1