Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from typing import Any, Callable
- class Ensure:
- def __init__(self, validate: Callable[[str], None], doc: str=None):
- self.validate = validate
- self.doc = doc
- def is_not_empty_str(name: str, value: str):
- print('Validating value: %s' % name)
- if not isinstance(value, str):
- raise ValueError('%s must be string' % name)
- if not bool(value):
- raise ValueError('%s may not be empty' % name)
- def do_ensure(Class):
- def make_property(name: str, attribute: Any) -> Class:
- privatName = "__" + name
- def getter(self):
- print("Getter for attribute: %s" % name)
- return getattr(self, privatName)
- def setter(self, value: Any):
- print("Getter for attribute: %s" % name)
- attribute.validate(name, value)
- setattr(self, privatName, 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
- @do_ensure
- class Book:
- book_name = Ensure(is_not_empty_str)
- author = Ensure(is_not_empty_str)
- def __init__(self, book_name: str, author: str):
- self.book_name = book_name
- self.author = author
- ___________________________________________________________
- Input:
- >> book = Book('title', 'author')
- Output:
- >> Setter for attribute: book_name
- >> Validating value: book_name
- >> Setter for attribute: author
- >> Validating value: author
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement