Skip to content

Instantly share code, notes, and snippets.

@danielballan
Created November 19, 2014 21:36
Show Gist options
  • Save danielballan/dc6f9f3ffcd00f2fa609 to your computer and use it in GitHub Desktop.
Save danielballan/dc6f9f3ffcd00f2fa609 to your computer and use it in GitHub Desktop.
YAML context
class YAML(object):
"""Open a YAML file as a dictionary in a context,
and update the file when the context is closed.
Example
-------
with YAML('data.yml') as data:
data['Trial A'] = {'foo': 1, 'bar': 2}
"""
def __init__(self, filepath):
self._filepath = filepath
try:
data = yaml.load(open(filepath))
except IOError:
data = {}
self._data = data
def __getitem__(self, key):
return self._data.__getitem__(self, key)
def __setitem__(self, key, val):
self._data.__setitem__(self, key, val)
def __enter__(self):
return self._data
def __exit__(self, type, value, traceback):
yaml.dump(self._data, open(self._filepath, 'w'),
default_flow_style=False)
@tacaswell
Copy link

That is pretty slick.

I would be a bit more careful in the init to make sure the issues is that the file does not exist, not that the path is non-existing/don't have permissions.

@tacaswell
Copy link

Should also probably support the full mutable-mapping interface.

@ericdill
Copy link

👍 to this being slick

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment