Skip to content

Instantly share code, notes, and snippets.

@shanemhansen
Forked from anonymous/gist:4675772
Created January 30, 2013 19:03
Show Gist options
  • Save shanemhansen/4675780 to your computer and use it in GitHub Desktop.
Save shanemhansen/4675780 to your computer and use it in GitHub Desktop.
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