Peter J. Holzer於 2019年11月4日星期一 UTC+8上午3時59分36秒寫道: > On 2019-11-01 04:24:38 -0700, jf...@ms4.hinet.net wrote: > > > The globals are your current module's namespace, and functions defines > > > in a module are bound to that module's namespace. > > > > > > Strip your test.py back. A lot. Try this: > > > > > > def main(): > > > print(rule) > > > > > > Now, let's use that: > > > > > > Python 3.7.4 (default, Sep 28 2019, 13:34:38) > > > [Clang 8.0.0 (clang-800.0.42.1)] on darwin > > > Type "help", "copyright", "credits" or "license" for more information. > > > >>> import test > > > >>> test.main() > > > Traceback (most recent call last): > > > File "<stdin>", line 1, in <module> > > > File "/Users/cameron/tmp/d1/test.py", line 2, in main > > > print(rule) > > > NameError: name 'rule' is not defined > > [Explanation snipped] > > > I didn't noticed that the interpreter has its own globals. Thanks for > > reminding. > > It's not really "the interpreter" (I think you mean the REPL) which has > it's own globals. Every module/file has its own globals. > > The same thing happens non-interactively: > > % cat test.py > def main(): > print(rule) > > % cat foo.py > #!/usr/bin/python3 > > from test import * > > rule = 42 > main() > > % ./foo.py > Traceback (most recent call last): > File "./foo.py", line 6, in <module> > main() > File "/home/hjp/tmp/test.py", line 2, in main > print(rule) > NameError: name 'rule' is not defined > > The "rule" identifier in main() refers to a "rule" variable in the > module test. If you set a variable "rule" somewhere else (in foo.py or > the REPL, ...), that has no effect. How should python know that you want > to set the rule variable in the test module? > > hp > > -- > _ | Peter J. Holzer | Story must make more sense than reality. > |_|_) | | > | | | h...@hjp.at | -- Charles Stross, "Creative writing > __/ | http://www.hjp.at/ | challenge!"
I innocently thought that when import module through "from test import *", I am working on test's globals under REPL. I didn't noticed the REPL has its own globals. >>> How should python know that you want to set the rule variable in the test >>> module? My 'wrong' answer will be, at the time I raised my question, that when import two different modules either has 'rule' variable, REPL will see the second imported one. No kidding:-) --Jach -- https://mail.python.org/mailman/listinfo/python-list