Skip to content

Instantly share code, notes, and snippets.

@danostrowski
Created November 27, 2012 00:44
Show Gist options
  • Save danostrowski/4151664 to your computer and use it in GitHub Desktop.
Save danostrowski/4151664 to your computer and use it in GitHub Desktop.
Context manager to allow getting an item from a dictionary and reusing
class get_item(object):
def __init__(self, d, i):
self.d = d
self.i = i
def __enter__(self):
if self.i in self.d:
return self.d[self.i]
return None
@danostrowski
Copy link
Author

This is a really silly context manager to avoid having to do:

if x in d:
  if isinstance(d[x], str):
    # do something with d[x]

...where x is a complex variable like "{0}/{1}/{2}".format(a, b, c) and you don't want to write it a bunch but you also don't want a local variable hanging around. So it ends up looking like:

with get_item(d, x) as myvar:
  if isinstance(myvar, str):
    # do something with myvar

... like I said, really silly. Probably too much Clojure today.

@danostrowski
Copy link
Author

And I only pasted it here to ask if there was something like this in stdlib already that I missed. (Which I'm pretty sure there isn't because it's silly.)

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