4

let's say i have the following files:

a.py

glo_var = 0
def func():
    global glo_var
    glo_var = 5
    print "A %d" % (glo_var)

b.py

from a import *
func()
print "B %d" % (glo_var)

If I ran b.py the output is:

A 5
B 0

My question is, how to import the global namespace so the output will be

A 5
B 5

I need to call the function in the module a.py from b.py so it will affect the globals.

I don't want to use regular "import" but to use it this way, "from a import *"

2
  • 3
    Please, do not do this in the real code. People will hate you. Commented Jun 20, 2011 at 9:58
  • The output value for A must be '0' not '5'. Commented Jun 20, 2011 at 11:16

1 Answer 1

4

Using from ... import ... copies the references from the other module. Rebinding the value in the original causes it to have a new reference, breaking the link between a.glo_var and b.glo_var permanently. Either use a mutable object and mutate it, or reimport a.glo_var whenever you need the updated value.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the quick answer, please explain your solution with the mutable object.
In a.py use e.g. glo_var = [0]. Then just read/write glo_var[0] instead of rebinding the name.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.