Closed kubinka0505 closed 2 years ago
This is an interesting idea, though I think this logic belong outside of the library.
To implement this, you first need the mapping of country_code
to currency
, which you can find in many places, for example this CSV file.
# Do not download the file at every execution :)
COUNTRIES_URL = "https://raw.githubusercontent.com/opentraveldata/opentraveldata/master/opentraveldata/optd_countries.csv"
import urllib.request
urllib.request.urlretrieve(COUNTRIES_URL, "countries.csv")
# Build the "country -> currency" mapping
country_to_currency = {}
with open("countries.csv") as f:
next(f) # skipping header
for row in f:
row = row.rstrip().split("^")
country_code, currency = row[0], row[10]
country_to_currency[country_code] = currency
# Expose a function to get the locale associated currency
from locale import getdefaultlocale
def get_locale_currency():
language_code, _ = getdefaultlocale()
country_code = language_code[-2:]
return country_to_currency[country_code]
# Use that function to retrieve the currency
import currency_converter as cc
c = cc.CurrencyConverter()
c.convert(125, "GBP", get_locale_currency())
...and since python 3.7 we can use locale.localeconv
to make this easier 🙂
No need to download anything.
>>> import locale
>>> import currency_converter as cc
>>> _ = locale.setlocale(locale.LC_ALL, "")
>>>
>>> def locale_curr(amount: float, from_: str = "USD", use_currency_name: bool = True):
... Converted = cc.CurrencyConverter().convert(
... float(amount),
... from_.upper().strip(),
... locale.localeconv()["int_curr_symbol"]
... )
... ResVal = [Converted]
... #-=-=-=-#
... __LCnv = locale.localeconv()
... if use_currency_name:
... ResVal += [__LCnv["currency_symbol"]]
... else:
... ResVal += [__LCnv["int_curr_symbol"]]
... #-=-=-=-#
... return tuple(ResVal)
...
>>> locale_curr(10, "USD", 1)
(40.63289979849789, 'zł')
>>> locale_curr(50, "USD", 0)
(203.16449899248946, 'PLN')
>>>```
I know it's obsolete,
and probably stupidbut is it possible to get target currency based on user'slocale.getdefaultlocale()
? On user demand of course.