开发者

Python expose to scope

开发者 https://www.devze.com 2023-03-26 20:22 出处:网络
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.

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?


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


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]


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消