Create a Python UDF (user-defined function) out of a callable. The output type of the UDF is determined based on its type annotation. Example: >>> import pathway as pw >>> import asyncio >>> table = pw.debug.table_from_markdown( ... ''' ... age | owner | pet ..
| 238 | |
| 239 | |
| 240 | class UDFFunction(UDF): |
| 241 | """Create a Python UDF (user-defined function) out of a callable. |
| 242 | |
| 243 | The output type of the UDF is determined based on its type annotation. |
| 244 | |
| 245 | Example: |
| 246 | |
| 247 | >>> import pathway as pw |
| 248 | >>> import asyncio |
| 249 | >>> table = pw.debug.table_from_markdown( |
| 250 | ... ''' |
| 251 | ... age | owner | pet |
| 252 | ... 10 | Alice | dog |
| 253 | ... 9 | Bob | dog |
| 254 | ... | Alice | cat |
| 255 | ... 7 | Bob | dog |
| 256 | ... ''' |
| 257 | ... ) |
| 258 | >>> |
| 259 | >>> @pw.udf |
| 260 | ... def concat(left: str, right: str) -> str: |
| 261 | ... return left + "-" + right |
| 262 | ... |
| 263 | >>> @pw.udf(propagate_none=True) |
| 264 | ... def increment(age: int) -> int: |
| 265 | ... assert age is not None |
| 266 | ... return age + 1 |
| 267 | ... |
| 268 | >>> res1 = table.select( |
| 269 | ... owner_with_pet=concat(table.owner, table.pet), new_age=increment(table.age) |
| 270 | ... ) |
| 271 | >>> pw.debug.compute_and_print(res1, include_id=False) |
| 272 | owner_with_pet | new_age |
| 273 | Alice-cat | |
| 274 | Alice-dog | 11 |
| 275 | Bob-dog | 8 |
| 276 | Bob-dog | 10 |
| 277 | >>> |
| 278 | >>> @pw.udf |
| 279 | ... async def sleeping_concat(left: str, right: str) -> str: |
| 280 | ... await asyncio.sleep(0.1) |
| 281 | ... return left + "-" + right |
| 282 | ... |
| 283 | >>> res2 = table.select(col=sleeping_concat(table.owner, table.pet)) |
| 284 | >>> pw.debug.compute_and_print(res2, include_id=False) |
| 285 | col |
| 286 | Alice-cat |
| 287 | Alice-dog |
| 288 | Bob-dog |
| 289 | Bob-dog |
| 290 | """ |
| 291 | |
| 292 | def __init__(self, func: Callable, **kwargs): |
| 293 | # this sets __wrapped__ |
| 294 | functools.update_wrapper(self, func) |
| 295 | super().__init__(**kwargs) |
| 296 | |
| 297 |