Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def statically_typed(*types, return_type=None):
- def decorator(function):
- @functools.wraps(function)
- def wrapper(*args, **kwargs):
- if len(args) > len(types):
- raise ValueError('too many arguments')
- if len(args) < len(types):
- raise ValueError('too few arguments')
- for i, (arg, type_) in enumerate(zip(args, types)):
- if not isinstance(arg, type_):
- raise ValueError('argument {} must be of type {}'
- .format(i, type_.__name__))
- result = function(*args, **kwargs)
- if (return_type is not None and not isinstance(result, return_type)):
- raise ValueError('return value must be of type {}'.format(return_type.__name__))
- return result
- return wrapper
- return decorator
- Examples:
- @statically_typed(str, int, str)
- def repeat(what, count, separator):
- return ((what + separator) * count)[:-len(separator)]
- @statically_typed(str, str, return_type=str)
- def make_tagged(text, tag):
- return '<{0}>{1}</{0}>'.format(tag, text)
- ---------------
- Class decorator
- ---------------
- def do_ensure(Class):
- def make_property(name, attribute):
- privateName = "__" + name
- def getter(self):
- return getattr(self, privateName)
- def setter(self, value):
- attribute.validate(name, value)
- return setattr(self, privateName, value)
- return property(getter, setter, doc=attribute.doc)
- for name, attribute in Class.__dict__.items():
- if isinstance(attribute, Ensure):
- setattr(Class, name, make_property(name, attribute))
- return Class
- class Ensure:
- def __init__(self, validate, doc=None):
- self.validate = validate
- self.doc = doc
- def is_non_empty_str(name, value):
- if not isinstance(value, str):
- raise ValueError('must be str')
- if not bool(value):
- raise ValueError('may not be empty')
- Example:
- @do_ensure
- class Book:
- title = Ensure(is_non_empty_str)
- author = Ensure(is_non_empty_str)
- def __init__(self, title, author):
- self.title = title
- self.author = author
- @property
- def value(self):
- return 'Title: %s. Author: %s' % (self.title, self.author)
- book = Book('Some title', 'First Name, Last Name')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement