Skip to content

Instantly share code, notes, and snippets.

@mpurdon
Created January 30, 2015 03:56
Show Gist options
  • Save mpurdon/c541b748fe911ffb31fe to your computer and use it in GitHub Desktop.
Save mpurdon/c541b748fe911ffb31fe to your computer and use it in GitHub Desktop.
Result object that can act like a string or a boolean when needed.
"""
Proof of concept
Returning a tuple is nice in python but it would be better if we could return
an object that was truthy when compared and stringy when cast as a string
@author Matthew Purdon
"""
from collections import namedtuple
class Result(namedtuple('Result', ['success', 'message'])):
"""
Represents a result and message
"""
def __str__(self):
return str(self.message)
def __bool__(self):
return self.success
# Point the Python 2 version at the Python 3 version
__nonzero__ = __bool__
def main():
good_result = Result(True, "Winning")
print good_result
print "yes" if good_result else "no"
bad_result = Result(False, "Fail Whale")
print bad_result
print "yes" if bad_result else "no"
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment