To learn about packaging, I've written a small script that converts a text string to Morse code.
I have a function that opens a JSON file and returns the contents as a dictionary. This function passes its pytest for the correct behavior and meets with MyPy's approval:
def json_via_importlib() -> dict[str, Any]:
'''Get data from `nato.json` and return it as a dictionary.
'''
try:
file_path = importlib.resources.files('morse_code').joinpath('nato.json')
with file_path.open('r', encoding='utf-8') as file:
data: dict[str, Any] = json.load(file)
return data
except Exception as e:
log.error(e)
raise
This is a helper function - any exception should bubble back to the convert_string
function that calls it.
I used try
here because importlib.resources
and open()
could throw exceptions. I used a blanket except
because the source code for importlib.resources
, has these - but I can't be sure this is all of them:
RuntimeError
NotADirectoryError
,IsADirectoryError
FileNotFoundError
KeyError
,Value Error
EDITED Questions:
- I use a lot of 3rd party packages. I can't see hunting down every possible error that could be thrown. Sometimes it seems like a blanket try / except is the best option. But is this true?
- Is there a way to collectively catch
importlib.resources
errors - meaning any error by a given module? - What's the proper use of try/except/raise for a helper function in relationship to the function that calls it?
- If there is a use case for a blanket try/except, how do you write a proper pytest to satisfy
coverage
? I see how to do it for specific errors, but not for this scenario.
Any help is much appreciated - thanks :)