Created
November 27, 2012 00:44
-
-
Save danostrowski/4151664 to your computer and use it in GitHub Desktop.
Context manager to allow getting an item from a dictionary and reusing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
This is a really silly context manager to avoid having to do:
...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:
... like I said, really silly. Probably too much Clojure today.