search

Home  >  Q&A  >  body text

python - Problem with variable scope in different files

Now there are two files:

a.py:

x=1
from b import *
printx()
b.py:

def printx():
    print(x)

When calling $ python3 a.py from the command line, there will be a NameError. I don’t understand here. When calling a.py directly, isn’t x considered a global variable? According to the LEGB rules, why does it go wrong?

某草草某草草2804 days ago585

reply all(1)I'll reply

  • phpcn_u1582

    phpcn_u15822017-05-18 10:52:10

    x is only visible in file a. Importing b in file a only makes the method printx in file b visible to file a. You can call it, and it does not change the invisibility of file x to file b. .

    reply
    0
  • Cancelreply