Skip to content

Instantly share code, notes, and snippets.

@domodomodomo
Last active March 2, 2018 09:48
Show Gist options
  • Save domodomodomo/d6e0144bfa789db2b6522aaa0cd765dd to your computer and use it in GitHub Desktop.
Save domodomodomo/d6e0144bfa789db2b6522aaa0cd765dd to your computer and use it in GitHub Desktop.
from abc import ABCMeta, abstractmethod
class Len(metaclass=ABCMeta):
@abstractmethod
def len(self):
"""Return length of object."""
raise NotImplementedError()
def checktype(method):
def decorated_method(*args, **kwargs):
val = method(*args, **kwargs)
if type(val) is not int:
raise TypeError('len method should return int')
else:
return val
return decorated_method
class Person(Len):
@Len.checktype
def len(self):
return 1
try:
person = Person()
print(person.len())
except Exception as err:
print(err)
class Dog(Len):
@Len.checktype
def len(self):
return 'Bow, bow!'
try:
dog = Dog()
print(dog.len()) # TypeError
except TypeError as err:
print(TypeError, err)
class Cat(Len):
pass
try:
cat = Cat() # NotImplementedError
print(cat.len())
except TypeError as err:
print(TypeError, err)
@domodomodomo
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment