How to make a variable's late binding crosses the module boundary?

Mark Bourne nntp.mbourne at spamgourmet.com
Sat Aug 27 07:42:13 EDT 2022


Jach Feng wrote:
> I have two files: test.py and test2.py
> --test.py--
> x = 2
> def foo():
>      print(x)
> foo()
> 
> x = 3
> foo()
> 
> --test2.py--
> from test import *
> x = 4
> foo()
> 
> -----
> Run test.py under Winows8.1, I get the expected result:
> e:\MyDocument>py test.py
> 2
> 3
> 
> But when run test2.py, the result is not my expected 2,3,4:-(
> e:\MyDocument>py test2.py
> 2
> 3
> 3
> 
> What to do?

`from test import *` does not link the names in `test2` to those in 
`test`.  It just binds objects bound to names in `test` to the same 
names in `test2`.  A bit like doing:

import test
x = test.x
foo = test.foo
del test

Subsequently assigning a different object to `x` in one module does not 
affect the object assigned to `x` in the other module.  So `x = 4` in 
`test2.py` does not affect the object assigned to `x` in `test.py` - 
that's still `3`.  If you want to do that, you need to import `test` and 
assign to `test.x`, for example:

import test
test.x = 4
test.foo()

-- 
Mark.


More information about the Python-list mailing list