python global variable inside a module

Question:

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?

Asked By: RatDon

||

Answers:

The way your code is structured, it implies to me that you’re treating import as if it were effectively copying-and-pasting the contents of b.py into a.py. However, that’s not how Python works — variables and functions inside one module will not be accessible in another unless explicitly passed in via a function, or by using the module.member notation.

Try doing this instead:

a.py:

import b

ip = raw_input()
b.show(ip)

b.py:

def show(ip):
    print ip

If you need to do some processing within the b module, pass in the relevant functions, make any changes, and return them. Then, reassign them within the calling module.

Edit: if you must use globals, change b.py to look like this:

ip = None

def show(temp):
    global ip
    ip = temp

    # code here

    print ip

…but it would be more ideal to restructure so that you don’t end up using globals.

Answered By: Michael0x2a

i moved some of the code of a.py to b.py like raw_input() and then the b.py just returns what is being needed in a.py.

so no need to worry about global variables etc. as half of the work is being done by b.py.

Answered By: RatDon

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.

Answered By: Marcin
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.