开发者

Python - Assign global variable to function return requires function to be global?

So, I'm confused. I have a module containing some function that I use in another module. Imported like so:

from <module> import *

Inside my module, there exist functions whose purpose is to set global variables in the main program.

main.py:

from functions import *

bar = 20
print bar
changeBar()
print bar

functions.py:

def changeBarHelper(variable):
    variable = variable * 2
    return variable

def changeBar():
    global bar
    bar = changeBarHelper(bar)

Now, this is a simplification, but it is the least code that yields the same result:

Traceback (most recent call last):
  File "/path/main.py", line 5, in 
        changeBar()
  File "/path/functions.py", line 7, in changeBar
    bar = changeBarHelper(bar)
NameError: global name 'ba开发者_运维技巧r' is not defined


Doing an import * in the way that you've done it is a one way process. You've imported a bunch of names, much the same way as you'd do:

from mymodule import foo, bar, baz, arr, tee, eff, emm

So they are all just assigned to names in the global scope of the module where the import is done. What this does not do is connect the global namespaces of these two modules. global means module-global, not global-to-all-modules. So every module might have its own fubar global variable, and assigning to one won't assign to every module.

If you want to access a name from another module, you must import it. So in this example:

def foo(var1, var2):
    global bar
    from mainmodule import fubar
    bar = fubar(var1)

By doing the import inside the function itself, you can avoid circular imports.


Well, I can't comment on any of the posts here and this solution isn't working. I would like to clarify this a bit.

There are two modules here:

main.py:

from functions import *

bar = 20
print bar
changeBar()
print bar

functions.py:

def changeBarHelper(variable):
    variable = variable * 2
    return variable

def changeBar():
    global bar
    bar = changeBarHelper(bar)

Now, this is a simplification, but it is the least code that yields the same result:

Traceback (most recent call last):
  File "/path/main.py", line 5, in 
    changeBar()
  File "/path/functions.py", line 7, in changeBar
    bar = changeBarHelper(bar)
NameError: global name 'bar' is not defined

Now, the solution given isn't working for me, and this is a problem I would really like a solution to.


def changeBar()

needs to be:

def changeBar(bar)

that way when you call changeBar(bar) in main.py

functions.py works on bar variable from main.py

sooo...

from functions import *

bar = 20
print bar
bar = changeBar(bar)
print bar

def changeBarHelper(variable):
    variable = variable * 2
    return variable

def changeBar(bar):
    bar = changeBarHelper(bar)
    return bar
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜