Skip to content

Propagate magic opt-out flags through MagicAlias - #15365

Open
l46983284-cpu wants to merge 1 commit into
ipython:mainfrom
l46983284-cpu:fix-13064-alias-no-var-expand
Open

Propagate magic opt-out flags through MagicAlias#15365
l46983284-cpu wants to merge 1 commit into
ipython:mainfrom
l46983284-cpu:fix-13064-alias-no-var-expand

Conversation

@l46983284-cpu

Copy link
Copy Markdown
Contributor

Fixes #13064

Magics created via %alias_magic don't carry the target magic's opt-out flags. run_line_magic/run_cell_magic read MAGIC_NO_VAR_EXPAND_ATTR, needs_local_scope and MAGIC_OUTPUT_CAN_BE_SILENCED off the registered object; on a MagicAlias those attributes don't exist, so {var} in an aliased call gets interpolated from user_ns before execution (the stale-i f-string symptom from the issue), and aliases of needs_local_scope magics lose access to function locals.

Give MagicAlias property delegates that resolve the aliased magic at call time — the class already documents late binding — and report the target's flags. The lookup walks alias chains iteratively and stops on cycles, so a self-referencing alias terminates and raises the original UsageError instead of recursing forever. A missing target yields False, i.e. today's behavior.

Regression tests (all in tests/test_magic.py):

  • test_alias_magic_no_var_expand — line alias of %time does not expand {a}
  • test_alias_magic_cell_no_var_expand — same through the cell path, %%timeit setup line
  • test_alias_magic_needs_local_scope — alias sees the caller's function locals
  • test_alias_magic_fstring_loop — exact repro from the issue
  • test_alias_magic_flag_lookup_on_self_loop — cyclic alias terminates

Checked in a fresh sandbox on upstream main (dd41c52): the new flag tests fail without the change as expected; with it, 130 passed, 6 skipped in tests/test_magic.py.

run_line_magic/run_cell_magic read MAGIC_NO_VAR_EXPAND_ATTR,
needs_local_scope and MAGIC_OUTPUT_CAN_BE_SILENCED off the registered
magic object. A MagicAlias carries none of them, so aliased calls to
%time et al. had {var} interpolated from user_ns before execution and
lost access to function locals (GH ipython#13064).

Give MagicAlias property delegates that resolve the aliased magic at
call time, preserving the documented late binding, and report the
target's flags. The lookup walks alias chains iteratively and stops on
cycles, so a self-referencing alias terminates and raises the original
UsageError instead of recursing forever. A missing target yields False,
i.e. today's behavior.

Adds five regression tests in tests/test_magic.py.

Signed-off-by: Alex Chen <l46983284@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Odd interaction with alias_magic and f-strings in for-loop

1 participant