Created
January 30, 2013 19:03
-
-
Save anonymous/4675772 to your computer and use it in GitHub Desktop.
the thingy operator for python
This file contains 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 maybe(object): | |
def __init__(self, original): | |
self.original = original | |
def __getattr__(self, attr): | |
if hasattr(self.original, attr): | |
return maybe(getattr(self.original, attr)) | |
return maybe(None) | |
def __call__(self): | |
return self.original | |
if __name__ == "__main__": | |
import os | |
expanduser = maybe(os).path.expanduser() | |
print expanduser('~/foo') | |
idontexist = maybe(os).foo.bar.baz() | |
assert idontexist is None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment