Created
January 30, 2015 04:00
-
-
Save mpurdon/7896c73c5ed77f7ef1c7 to your computer and use it in GitHub Desktop.
Playing with exceptions through inherited methods.
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
""" | |
Proof of Concept | |
Following the course of an exception in a class hierarchy similar to that | |
in Django views. | |
@author Matthew Purdon | |
""" | |
class Parent(object): | |
def dispatch(self, method, value): | |
handler_name = 'handle_{}'.format(method) | |
handler = getattr(self, handler_name) | |
print 'Dispatching handler {}'.format(handler_name) | |
return handler(value) | |
class Child(Parent): | |
class BadValueException(ValueError): | |
def __init__(self, value, *args, **kwargs): | |
self.value = value | |
super(Child.BadValueException, self).__init__(*args, **kwargs) | |
def dispatch(self, method, value): | |
try: | |
print 'Dispatching from child' | |
return super(Child, self).dispatch(method, value) | |
except self.BadValueException as error: | |
print 'Exception caught: {}'.format(str(error)) | |
def raises_exception(self, value): | |
print 'Raising exception for {}'.format(value) | |
raise self.BadValueException(value, 'Bad value "{}" passed in'.format(value)) | |
class GrandChild(Child): | |
def handle_int(self, value): | |
print 'Handling value {}'.format(value) | |
return self.raises_exception(value) | |
def handle_float(self, value): | |
print 'Converted {} to {}'.format(value, float(value)) | |
if __name__ == "__main__": | |
thing = GrandChild() | |
thing.dispatch('int', 'a') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment