bcf
bcf

Reputation: 2134

%run Python function in IPython

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?

Upvotes: 2

Views: 1689

Answers (2)

hpaulj
hpaulj

Reputation: 231385

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.

Upvotes: 1

Sosel
Sosel

Reputation: 1718

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

Upvotes: 1

Related Questions