neovim / pynvim

Python client and plugin host for Nvim
http://pynvim.readthedocs.io/en/latest/
Apache License 2.0
1.48k stars 118 forks source link

Local python variables are not defined when using `py3eval` from within a separate python file #501

Closed smjonas closed 9 months ago

smjonas commented 2 years ago

First of all, I apologize if this is not the right place for this question.

Let's say I have the following python code:

import vim
x = 1
print(vim.eval("py3eval('x')"))

Now I use this code in a vim function in the file myplugin/autoload/myplugin.vim:

function! myplugin#myfunction()
python3 << EOF
import vim
x = 1
print(vim.eval("py3eval('x')"))
EOF
endfunction

Calling this function from vim or lua (vim.fn["myplugin#mytest"]()) prints 1 as expected.

However, I get an error when I try the following:

I get the following error:

NameError: name 'x' is not defined

I expected both implementations to work exactly the same (it should not matter whether the code is defined in a python3 << block or in a separate python file). Why is x not defined in the second case?

Edit: changed pyeval to py3eval

wookayin commented 9 months ago

x=1 here has a local scope, so there is no way for external expressions (py3eval) to look at the local variable. This is as designed and you should therefore use a global (or nonlocal) variable.