0

I am using Jupyter Notebook for some ad-hoc analysis. I wrap some codes up using functions so my notebook will not be very long. However, when I try to move functions to a module (*.py) and import it into my notebook, those functions cannot access the global variables I define in the notebook.

a = 1

def func_in_notebook():
  print(a)

func_in_notebook()

This works; but when I try to import the function from a module, it doesn't work:

Firstly I save the following as "utility.py"

def func_from_module():
  print(a)

And the following gives me the error:

from utility import func_from_module
a = 1
func_from_module()

NameError: name 'a' is not defined

I know I can simply add "a" as the function argument, but in reality, I may have more than 20 global variables I need for my function to run, and I hope to avoid identifying all global variables I need for the function to work. Is there a way I can import the function from a module to the global, so the f has the access to global variables; or simply make the module see all global variables I define in the notebook?

Thanks in advance.

Ken White
  • 120,522
  • 13
  • 212
  • 426
chl111
  • 448
  • 3
  • 14
  • Does this answer your question? [Visibility of global variables in imported modules](https://stackoverflow.com/questions/15959534/visibility-of-global-variables-in-imported-modules) – Josh Friedlander Jan 05 '22 at 11:45

0 Answers0