As an example, let's say we are checking a preferences.json
file with the contents of
preferences.json
{
"background_color": "red"
}
Then we read/modify/write the preferences back using the Python json module. The following two examples both function the same except one uses the open()
context manager and one doesn't.
change_pref_with_CM.py
import json
# Load the user preferences
with open('preferences.json') as prefs_file:
prefs = json.load(prefs_file)
print(prefs['background_color']) # Prints 'red'
# Change the user's background_color preference to blue
prefs['background_color'] = 'blue'
# Save the user preferences
with open('preferences.json', 'w') as prefs_file:
json.dump(prefs, prefs_file)
change_pref_without_CM.py
import json
# Load the user preferences
prefs = json.load(open('preferences.json'))
print(prefs['background_color']) # Prints 'red'
# Change the user's background_color preference to blue
prefs['background_color'] = 'blue'
# Save the user preferences
prefs = json.dump(prefs, open('preferences.json', 'w'))
For normal file reading/writing I always use a context manager and handle all logic inside the context manager. But in this example the file is being used just long enough to either populate a dict or write a dict to a file. So the example not using a context manager seems much cleaner to me. I worry that since the files are being opened "anonymously" there is nothing to call close()
on and I don't know if the json module handles that with a context manager internally or if I would just be leaking file descriptors. I'm sure using a context manager just in case is the safe way to go, but at the same time I would like to know how the json module handles file descriptors (or is it file objects?)
I went looking for the source for the json module but after finding it and searching for "dump" and "load" and finding nothing I'm not sure what to check next. I'm not nearly proficient enough with C to understand what's going on in there.