2

I'd like to run a function from IPython and load all of its data into the interactive namespace, just like how %run filename.py does it. E.g., here's the file scratch.py:

def foo(x):
    a = x*2

In IPython, I'd like to run this function and be able to access the name a. Is there a way to do this?

bcf
  • 2,104
  • 1
  • 24
  • 43

2 Answers2

1

In order to make the variable available globally (or in some interactive IPython session), you first have to define it as global:

def foo(x):
    global a
    a = x*2

Otherwise your a remains a local variable within your function. More infos e.g. here: Use of “global” keyword in Python

Community
  • 1
  • 1
Sosel
  • 1,678
  • 1
  • 16
  • 31
  • How can I call `foo` from IPython to access `a`, then? I've tried `from scratch import foo` then `foo(2)`, but I still get a NameError when I then type `a` saying it is not defined. – bcf Jul 11 '16 at 14:19
  • Add `return a` at the end of the function. – Sosel Jul 14 '16 at 08:02
1

This isn't a ipython or %run issue, but rather a question of what you can do with variables created with a function. It applies to any function run in Python.

A function has a local namespace, where it puts the variables that you define in that function. That is, by design, local to the function - it isn't supposed to 'bleed' into the calling namespare (global of the module or local of the calling function). This is a major reason from using functions - to isolate it's variables from the calling one.

If you need to see the variables in a function you can do several things:

  • use global (often a sign of poor design)
  • use local prints (temporary, for debugging purposes)
  • return the values (normal usage)
  • use a debugger.

This is a useless function:

def foo(x):
    a = x*2

this may have some value

def foo(x):
    a = x*2
    return a

def foo(x):
    a = x*2
    print(a)     # temporary debugging print
    # do more with a and x
    return ...    

In a clean design, a function takes arguments, and returns values, with a minimum of side effects. Setting global variables is a side effect that makes debugging your code harder.

hpaulj
  • 221,503
  • 14
  • 230
  • 353