pylance-release icon indicating copy to clipboard operation
pylance-release copied to clipboard

Assign to variable from commented-out magic command

Open janosh opened this issue 3 years ago • 5 comments
trafficstars

IPython allows expanding Python variables into magic shell commands and also assigning the command's stdout to a variable:

# %%
num = 42
stdout = !echo {num} # raises: Pylance: Expected expression
print(stdout)
>>> ['42']

But it seems there's no way to do this without syntax error.

https://github.com/microsoft/vscode-jupyter/issues/3263 introduced "jupyter.magicCommandsAsComments": true which allows to do:

slurm_cmd = """
sbatch --partition icelake --account=SL3-CPU --time 1 --nodes 1 --wrap "python -c 'print(42)'"
"""
slurm_msg = ""
#! slurm_msg = {slurm_cmd}

print(f"{slurm_msg=} at {datetime.now():%Y-%m-%d %H-%M}")
>>> slurm_msg='' at 2022-04-24 20-04

The shell command runs as expected but the variable assignment is lost. Any chance magicCommandsAsComments could get a feature upgrade?

janosh avatar Apr 24 '22 19:04 janosh

@janosh looks like there are two issues here. One is the syntax error and the other is variable value being lost. Is that correct?

DonJayamanne avatar Apr 26 '22 20:04 DonJayamanne

Transferring to lsp-middle-ware to ensure statements such as stdout = !echo {num} are not flagged as errors.

DonJayamanne avatar Apr 26 '22 20:04 DonJayamanne

@DonJayamanne That's correct, 2 issues here, though the syntax error can be worked around as in the 2nd code snippet with this clunky construction.

slurm_msg = ""
#! slurm_msg = {slurm_cmd}

So the only real issue is the variable assignment being lost. But if there's a proper solution to the syntax error (maybe marking it as acceptable code in pylance), this could fix the lost assignment as well and in a cleaner way.

janosh avatar Apr 27 '22 08:04 janosh

The middleware layer is being deprecated (and well never handled this sort of thing anyway). Might be something to do in pylance itself.

rchiodo avatar Jul 29 '22 17:07 rchiodo

there seems an issue with ipython mode

heejaechang avatar Aug 01 '22 17:08 heejaechang

I ran into a similar problem

image

hyacz avatar Nov 15 '22 02:11 hyacz