Creates a new type handler with the specified type-casting handler
(
doc=None,
error_text=None,
exception_handlers=empty.dict,
extend=Type,
chain=True,
auto_instance=True,
accept_context=False,
)
| 61 | |
| 62 | |
| 63 | def create( |
| 64 | doc=None, |
| 65 | error_text=None, |
| 66 | exception_handlers=empty.dict, |
| 67 | extend=Type, |
| 68 | chain=True, |
| 69 | auto_instance=True, |
| 70 | accept_context=False, |
| 71 | ): |
| 72 | """Creates a new type handler with the specified type-casting handler""" |
| 73 | extend = extend if type(extend) == type else type(extend) |
| 74 | |
| 75 | def new_type_handler(function): |
| 76 | class NewType(extend): |
| 77 | __slots__ = () |
| 78 | _accept_context = accept_context |
| 79 | |
| 80 | if chain and extend != Type: |
| 81 | if error_text or exception_handlers: |
| 82 | if not accept_context: |
| 83 | |
| 84 | def __call__(self, value): |
| 85 | try: |
| 86 | value = super(NewType, self).__call__(value) |
| 87 | return function(value) |
| 88 | except Exception as exception: |
| 89 | for take_exception, rewrite in exception_handlers.items(): |
| 90 | if isinstance(exception, take_exception): |
| 91 | if isinstance(rewrite, str): |
| 92 | raise ValueError(rewrite) |
| 93 | else: |
| 94 | raise rewrite(value) |
| 95 | if error_text: |
| 96 | raise ValueError(error_text) |
| 97 | raise exception |
| 98 | |
| 99 | else: |
| 100 | if extend._accept_context: |
| 101 | |
| 102 | def __call__(self, value, context): |
| 103 | try: |
| 104 | value = super(NewType, self).__call__(value, context) |
| 105 | return function(value, context) |
| 106 | except Exception as exception: |
| 107 | for take_exception, rewrite in exception_handlers.items(): |
| 108 | if isinstance(exception, take_exception): |
| 109 | if isinstance(rewrite, str): |
| 110 | raise ValueError(rewrite) |
| 111 | else: |
| 112 | raise rewrite(value) |
| 113 | if error_text: |
| 114 | raise ValueError(error_text) |
| 115 | raise exception |
| 116 | |
| 117 | else: |
| 118 | |
| 119 | def __call__(self, value, context): |
| 120 | try: |