0

Let's consider we have a module called mod which has a function func. I want to import the module and run func, exposing a variable var to its scope.

a.func() # and func can do stuff with var

How can i do this?

nikitautiu
  • 951
  • 1
  • 14
  • 28
  • I don't actually want to pass it to the function, func is for scripting actually. I just want to expose some variables to it as globals. – nikitautiu Aug 09 '11 at 18:56

3 Answers3

2

Either you import the module where var is defined into your mod module, or you pass var as an argument to func().

Nicola Musatti
  • 17,834
  • 2
  • 46
  • 55
  • After all this might be the most elegant solution. I might pass a class containing all the variables, or even pass a module. – nikitautiu Aug 09 '11 at 19:09
0

Most likely, you should add an argument to func() through which to pass in the variable var. If you want func() to modify var, then have the function return the new value. (If necessary you can easily have multiple return values).

Community
  • 1
  • 1
zoo
  • 1,901
  • 1
  • 17
  • 25
0

Pass the variable to the function. Works the same across modules as it does in a single module.

# module a
def func(v):
    print v

# module b
import a
var=42
a.func(var)

If you need to modify the value, return it. The caller then can put it wherever they want, including back into the same variable.

# module a
def func(v):
    return v + 1

# module b
import a
var=42
var = a.func(var)   # var is now 43

Some objects, such as lists, are mutable and can be changed by the function. You don't have to return those. Sometimes it is convenient to return them, but I'll show it without.

# module a
def func(v):
    v.append(42)

# module b
import a
var=[]        # empty list
a.func(var)   # var is now [42]
kindall
  • 178,883
  • 35
  • 278
  • 309