Simple magic to quickly define a code transformer for all IPython's future input. ``__code__`` and ``__ret__`` are special variable that represent the code to run and the value of the last expression of ``__code__`` respectively. Examples --------
(self, line, cell=None)
| 1614 | ) |
| 1615 | @line_cell_magic |
| 1616 | def code_wrap(self, line, cell=None): |
| 1617 | """ |
| 1618 | Simple magic to quickly define a code transformer for all IPython's future input. |
| 1619 | |
| 1620 | ``__code__`` and ``__ret__`` are special variable that represent the code to run |
| 1621 | and the value of the last expression of ``__code__`` respectively. |
| 1622 | |
| 1623 | Examples |
| 1624 | -------- |
| 1625 | |
| 1626 | .. ipython:: |
| 1627 | |
| 1628 | In [1]: %%code_wrap before_after |
| 1629 | ...: print('before') |
| 1630 | ...: __code__ |
| 1631 | ...: print('after') |
| 1632 | ...: __ret__ |
| 1633 | |
| 1634 | |
| 1635 | In [2]: 1 |
| 1636 | before |
| 1637 | after |
| 1638 | Out[2]: 1 |
| 1639 | |
| 1640 | In [3]: %code_wrap --list |
| 1641 | before_after |
| 1642 | |
| 1643 | In [4]: %code_wrap --list-all |
| 1644 | before_after : |
| 1645 | print('before') |
| 1646 | __code__ |
| 1647 | print('after') |
| 1648 | __ret__ |
| 1649 | |
| 1650 | In [5]: %code_wrap --remove before_after |
| 1651 | |
| 1652 | """ |
| 1653 | args = magic_arguments.parse_argstring(self.code_wrap, line) |
| 1654 | |
| 1655 | if args.list: |
| 1656 | for name in self._transformers.keys(): |
| 1657 | print(name) |
| 1658 | return |
| 1659 | if args.list_all: |
| 1660 | for name, _t in self._transformers.items(): |
| 1661 | print(name, ":") |
| 1662 | print(indent(ast.unparse(_t.template), " ")) |
| 1663 | print() |
| 1664 | return |
| 1665 | |
| 1666 | to_remove = self._transformers.pop(args.name, None) |
| 1667 | if to_remove in self.shell.ast_transformers: |
| 1668 | self.shell.ast_transformers.remove(to_remove) |
| 1669 | if cell is None or args.remove: |
| 1670 | return |
| 1671 | |
| 1672 | _trs = ReplaceCodeTransformer(ast.parse(cell)) |
| 1673 |
nothing calls this directly
no test coverage detected