Wrap a function to a closure function. Before: >>> def fn(x): ... After: >>> def create_fn(): ... closure_var_1 = None ... ... def fn(x): ... ... ... return fn ... ... ... fn = create_fn()
(tree: gast.AST, closure_vars: list[str])
| 477 | |
| 478 | |
| 479 | def wrap_as_closure(tree: gast.AST, closure_vars: list[str]) -> gast.AST: |
| 480 | """ |
| 481 | Wrap a function to a closure function. |
| 482 | |
| 483 | Before: |
| 484 | |
| 485 | >>> def fn(x): ... |
| 486 | |
| 487 | After: |
| 488 | |
| 489 | >>> def create_fn(): |
| 490 | ... closure_var_1 = None |
| 491 | ... |
| 492 | ... def fn(x): ... |
| 493 | ... |
| 494 | ... return fn |
| 495 | ... |
| 496 | ... |
| 497 | ... fn = create_fn() |
| 498 | """ |
| 499 | |
| 500 | def create_assign_node(name, value) -> gast.Assign: |
| 501 | return gast.Assign( |
| 502 | targets=[ |
| 503 | gast.Name( |
| 504 | id=name, |
| 505 | ctx=gast.Store(), |
| 506 | annotation=[], |
| 507 | type_comment=[], |
| 508 | ) |
| 509 | ], |
| 510 | value=value, |
| 511 | type_comment=None, |
| 512 | ) |
| 513 | |
| 514 | def create_wrppper_fn_def_node(name, body) -> gast.FunctionDef: |
| 515 | return gast.FunctionDef( |
| 516 | name=name, |
| 517 | args=gast.arguments( |
| 518 | args=[], |
| 519 | posonlyargs=[], |
| 520 | vararg=None, |
| 521 | kwonlyargs=[], |
| 522 | kw_defaults=[], |
| 523 | kwarg=None, |
| 524 | defaults=[], |
| 525 | ), |
| 526 | body=body, |
| 527 | decorator_list=[], |
| 528 | returns=None, |
| 529 | type_comment=None, |
| 530 | type_params=[], |
| 531 | ) |
| 532 | |
| 533 | if not isinstance(tree, gast.Module): |
| 534 | return tree |
| 535 | if len(tree.body) != 1: |
| 536 | return tree |
no test coverage detected