0

So I have a jupyternotebook main.ipynb. I have to submodules named x.py and y.py. x.py contains the line x = 30 and y.py contains the line y = 2*z

I know how I can use the variable defined in the secondary file by using it as an attribute of that file. For instance, in main.ipynb's first cell, I import x and then run print (x.x) it works ok.

Now, in the next cell if I define a variable z= 15. and then I import y.py I get the following err

NameError: name 'z' is not defined

My question is, how do I make the submodule y recognize variable z which is in the global namespace.

  • Is the only line in `y.py` right now, `y = 2*z`? If so, you wouldn't import it as there's nothing complete to import. (Hence, the syntax error you see when you try.) If you want to execute that script `y.py` with the setting of `z` presently in `main.ipynb` namespace, you'd put in the next cell, below `z = 15`, the following: `%run -i y.py`. Read about the `-i` flag for `%run` [here](https://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-run). – Wayne Dec 02 '22 at 18:16
  • [Here](https://www.pythonlikeyoumeanit.com/Module5_OddsAndEnds/Modules_and_Packages.html#Modules) shows a concise example of how you could define a function in `y.py` so that you could pass in `z` from `main.ipynb` when you use the function from `y.py` after import. – Wayne Dec 02 '22 at 18:27
  • If you had a line in `y.py` where you set `z` that would make it complete and you could import it but `z` won't be substitutable unless you make `y=2*z` a function. Then you could swap in your setting for `z` in `main.ipynb` similar to [here](https://www.geeksforgeeks.org/how-to-import-variables-from-another-file-in-python/). – Wayne Dec 02 '22 at 18:39

0 Answers0