fork download
  1. ''' require_decorator1.py
  2. creating a general safe decorator
  3. a safe decorator can be combined with other decorators
  4. py2 and py3 tested
  5. '''
  6.  
  7. def require(expr):
  8. """a general decorator checking args requirement"""
  9. def decorator(func):
  10. def wrapper(*__args,**__kw):
  11. message = "failed precondition %s" % expr
  12. assert eval(expr), message
  13. return func(*__args,**__kw)
  14. # optional next 3 lines make decorator safe
  15. wrapper.__name__ = func.__name__
  16. wrapper.__dict__ = func.__dict__
  17. wrapper.__doc__ = func.__doc__
  18. return wrapper
  19. return decorator
  20.  
  21. # allows only 1 argument here
  22. @require("len(__args)==1")
  23. def test(*args):
  24. print(args[0])
  25.  
  26. # no problem, prints Hello world!
  27. test("Hello world!")
  28.  
  29. print('-'*50)
  30.  
  31. # has 2 arguments and will fail showing
  32. # AssertionError: failed precondition len(__args)==1
  33. test("Hello", "World")
Runtime error #stdin #stdout 0.02s 5824KB
stdin
Standard input is empty
stdout
Hello world!
--------------------------------------------------