From b1a046bdf51a0a2cdf051816fec5ef9a397cc840 Mon Sep 17 00:00:00 2001 From: lucaszw Date: Mon, 20 Jan 2020 11:16:52 -0500 Subject: [PATCH] support for variables in multi-line statements --- src/sql/magic.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/sql/magic.py b/src/sql/magic.py index 58812a40f..b63820653 100644 --- a/src/sql/magic.py +++ b/src/sql/magic.py @@ -1,4 +1,5 @@ import re +from string import Formatter from IPython.core.magic import Magics, magics_class, cell_magic, line_magic, needs_local_scope from IPython.display import display_javascript try: @@ -75,6 +76,13 @@ def execute(self, line, cell='', local_ns={}): mysql+pymysql://me:mypw@localhost/mydb """ + # Parse variables (words wrapped in {}) for %%sql magic (for %sql this is done automatically) + cell_variables = [fn for _, fn, _, _ in Formatter().parse(cell) if fn is not None] + cell_params = {} + for variable in cell_variables: + cell_params[variable] = local_ns[variable] + cell = cell.format(**cell_params) + # save globals and locals so they can be referenced in bind vars user_ns = self.shell.user_ns.copy() user_ns.update(local_ns)