Skip to content

Commit 7e0bb80

Browse files
committed
Lazy load currency data from json file
Removing duplicate code, and preventing redundant disk reads
1 parent 4e826b3 commit 7e0bb80

File tree

1 file changed

+11
-9
lines changed

1 file changed

+11
-9
lines changed

forex_python/converter.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -118,20 +118,22 @@ def convert(self, base_cur, dest_cur, amount, date_obj=None):
118118
class CurrencyCodes:
119119

120120
def __init__(self):
121-
pass
121+
self.__currency_data = None
122+
123+
@property
124+
def _currency_data(self):
125+
if self.__currency_data is None:
126+
file_path = os.path.dirname(os.path.abspath(__file__))
127+
with open(file_path + '/raw_data/currencies.json') as f:
128+
self.__currency_data = json.loads(f.read())
129+
return self.__currency_data
122130

123131
def _get_data(self, currency_code):
124-
file_path = os.path.dirname(os.path.abspath(__file__))
125-
with open(file_path + '/raw_data/currencies.json') as f:
126-
currency_data = json.loads(f.read())
127-
currency_dict = next((item for item in currency_data if item["cc"] == currency_code), None)
132+
currency_dict = next((item for item in self._currency_data if item["cc"] == currency_code), None)
128133
return currency_dict
129134

130135
def _get_data_from_symbol(self, symbol):
131-
file_path = os.path.dirname(os.path.abspath(__file__))
132-
with open(file_path + '/raw_data/currencies.json') as f:
133-
currency_data = json.loads(f.read())
134-
currency_dict = next((item for item in currency_data if item["symbol"] == symbol), None)
136+
currency_dict = next((item for item in self._currency_data if item["symbol"] == symbol), None)
135137
return currency_dict
136138

137139
def get_symbol(self, currency_code):

0 commit comments

Comments
 (0)