Skip to content

Instantly share code, notes, and snippets.

@el-hult
Last active August 22, 2019 19:22
Show Gist options
  • Save el-hult/14696a7bae067d80c7bd9d538160c29e to your computer and use it in GitHub Desktop.
Save el-hult/14696a7bae067d80c7bd9d538160c29e to your computer and use it in GitHub Desktop.
An example on how one can use the typings module to make currency conversion work like a charm. The code uses only python 3.7 features.
import urllib.request
import json
import typing
import functools
SEK = typing.NewType('SEK',float)
EUR = typing.NewType('EUR', float)
ConversionRate = typing.NewType('ConversionRate',float)
ThreeLetterCurrencyCode = str # ISO4217
ApiResponse = typing.Dict
@functools.lru_cache(maxsize=10)
def get_api_response() -> ApiResponse:
url = "https://api.exchangerate-api.com/v4/latest/" + "EUR"
contents = urllib.request.urlopen(url).read()
return json.loads(contents)
def extract_conversion_to(api_response: ApiResponse, to: ThreeLetterCurrencyCode) -> ConversionRate:
return api_response['rates'][to]
def eur_to_sek(rate:ConversionRate,eur:EUR) -> SEK:
return SEK(rate*eur)
full_response = get_api_response()
current_rate = extract_conversion_to(full_response,'SEK')
a = EUR(2.3)
b = eur_to_sek(current_rate,a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment