3

I'm sure someone's already answered this, but I can't find it.

I have a script test.py who's sole purpose of existence is to place the variable var into the global namespace:

def test():
    global var
    var = 'stuff'

Here's what happens when I run test.py in ipython using %run, then run test(), and then try to access var.

Python 3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 10:22:32) [MSC v.1900 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: %run test.py

In [2]: test()

In [3]: var
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-3-84ddba356ca3> in <module>()
----> 1 var

NameError: name 'var' is not defined

In [4]:

Any idea what's happening? Or how to generally bring it into the local namespace?

James Wright
  • 1,293
  • 2
  • 16
  • 32
  • Possible duplicate of [Is it possible to define global variables in a function in Python](https://stackoverflow.com/questions/13627865/is-it-possible-to-define-global-variables-in-a-function-in-python) – Bruno Henrique May 01 '18 at 20:02
  • The question technically is a duplicate, but I was still running into the issue. Turns out the issue was not in the global variable part, but in the way I was using IPython. I've updated the question and title to reflect the actual issue present. – James Wright May 02 '18 at 12:19

2 Answers2

5

The %run command creates a separate namespace for global variables in the file. It also updates the IPython interactive namespace with all variables defined in the file after execution. So you can either call the function in your script so that the global variable gets created before the file finishes executing:

def test():
    global var
    var = 'stuff'
test()

or use %run -i:

-i run the file in IPython’s namespace instead of an empty one. This is useful if you are experimenting with code written in a text editor which depends on variables defined interactively.

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
2

Use %run -i test.py this will run it in the interactive namespace and let you access the global variables.

In [1]: %run -i test.py

In [2]: test()

In [3]: var
Out[3]: 'stuff'
Auzy
  • 41
  • 4