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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Add return a at the end of the function.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.