views:

58

answers:

2

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.

Some of the global variables need to be assigned to the output of another function in that same module.

Example:

def fubar(var):
    var *= 2
    return var

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

But I encounter this error:

Traceback (most recent call last):
  File "blah", line 92, in setup_configs
    bar = fubar(var1)
NameError: global name 'fubar' is not defined

And I'm wondering, do I have to set the function I am referring to as global for this to work? It seems kinda... funny.

+1  A: 

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.

Jerub
A: 

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 doesn't do jack sh!t, and this is a problem I would really like a solution to. If I find one, I'll post it here and on my blog.

Also, who here noticed that StackOverflow is using John Gruber's MarkDown project for posting?

Dakota