A converter that composes multiple converters into one. When called on a value, it runs all wrapped converters, returning the *last* value. Type annotations will be inferred from the wrapped converters', if they have any. :param callables converters: Arbitrary number of c
(*converters)
| 3118 | |
| 3119 | |
| 3120 | def pipe(*converters): |
| 3121 | """ |
| 3122 | A converter that composes multiple converters into one. |
| 3123 | |
| 3124 | When called on a value, it runs all wrapped converters, returning the |
| 3125 | *last* value. |
| 3126 | |
| 3127 | Type annotations will be inferred from the wrapped converters', if |
| 3128 | they have any. |
| 3129 | |
| 3130 | :param callables converters: Arbitrary number of converters. |
| 3131 | |
| 3132 | .. versionadded:: 20.1.0 |
| 3133 | """ |
| 3134 | |
| 3135 | def pipe_converter(val): |
| 3136 | for converter in converters: |
| 3137 | val = converter(val) |
| 3138 | |
| 3139 | return val |
| 3140 | |
| 3141 | if not PY2: |
| 3142 | if not converters: |
| 3143 | # If the converter list is empty, pipe_converter is the identity. |
| 3144 | A = typing.TypeVar("A") |
| 3145 | pipe_converter.__annotations__ = {"val": A, "return": A} |
| 3146 | else: |
| 3147 | # Get parameter type. |
| 3148 | sig = None |
| 3149 | try: |
| 3150 | sig = inspect.signature(converters[0]) |
| 3151 | except (ValueError, TypeError): # inspect failed |
| 3152 | pass |
| 3153 | if sig: |
| 3154 | params = list(sig.parameters.values()) |
| 3155 | if ( |
| 3156 | params |
| 3157 | and params[0].annotation is not inspect.Parameter.empty |
| 3158 | ): |
| 3159 | pipe_converter.__annotations__["val"] = params[ |
| 3160 | 0 |
| 3161 | ].annotation |
| 3162 | # Get return type. |
| 3163 | sig = None |
| 3164 | try: |
| 3165 | sig = inspect.signature(converters[-1]) |
| 3166 | except (ValueError, TypeError): # inspect failed |
| 3167 | pass |
| 3168 | if sig and sig.return_annotation is not inspect.Signature().empty: |
| 3169 | pipe_converter.__annotations__[ |
| 3170 | "return" |
| 3171 | ] = sig.return_annotation |
| 3172 | |
| 3173 | return pipe_converter |
no test coverage detected