Advertisement
Woobinda

Validation of types, private attributes implementation

Feb 3rd, 2020
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.43 KB | None | 0 0
  1. from typing import Any, Callable
  2.  
  3.  
  4. class Ensure:
  5.  
  6.     def __init__(self, validate: Callable[[str], None], doc: str=None):
  7.         self.validate = validate
  8.         self.doc = doc
  9.  
  10.  
  11. def is_not_empty_str(name: str, value: str):
  12.     print('Validating value: %s' % name)
  13.  
  14.     if not isinstance(value, str):
  15.         raise ValueError('%s must be string' % name)
  16.  
  17.     if not bool(value):
  18.         raise ValueError('%s may not be empty' % name)
  19.  
  20.  
  21. def do_ensure(Class):
  22.     def make_property(name: str, attribute: Any) -> Class:
  23.         privatName = "__" + name
  24.  
  25.         def getter(self):
  26.             print("Getter for attribute: %s" % name)
  27.             return getattr(self, privatName)
  28.  
  29.         def setter(self, value: Any):
  30.             print("Getter for attribute: %s" % name)
  31.             attribute.validate(name, value)
  32.             setattr(self, privatName, value)
  33.  
  34.         return property(getter, setter, doc=attribute.doc)
  35.  
  36.     for name, attribute in Class.__dict__.items():
  37.         if isinstance(attribute, Ensure):
  38.             setattr(Class, name, make_property(name, attribute))
  39.  
  40.     return Class
  41.  
  42.  
  43. @do_ensure
  44. class Book:
  45.  
  46.     book_name = Ensure(is_not_empty_str)
  47.     author = Ensure(is_not_empty_str)
  48.  
  49.     def __init__(self, book_name: str, author: str):
  50.         self.book_name = book_name
  51.         self.author = author
  52.  
  53.  
  54. ___________________________________________________________
  55. Input:
  56. >> book = Book('title', 'author')
  57.  
  58. Output:
  59. >> Setter for attribute: book_name
  60. >> Validating value: book_name
  61. >> Setter for attribute: author
  62. >> Validating value: author
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement