Search code examples
pythonmoduleglobal-variables

python global variable inside a module


a.py contains:

ip=raw_input()
import b
show()

b.py contains:

def show:
    global ip
    print ip

it's showing an error saying that ip is not defined. how can i use a variable from the main script inside a module?


Solution

  • A global declaration prevents a local variable being created by an assignment. It doesn't magically search for a variable.

    Unless you import a variable from one module to another, it is not available in other modules.

    For b to be able to access members of a, you would need to import a. You can't, because a imports b.

    The solution here is probably just not to use global variables at all.