0

In config.py, I have:

config = 0
#config = []
def init_config():
    global config
    config = 1
    #config.append("1")
    print("init", config)

In main.py, I have:

from config import init_config
from config import config

def main():
    init_config()
    print("main", config)

if __name__ == '__main__':
    main()

And both the config.py and the main.py in the same directory. After running python main.py, I got:

init 1
main 0

But if I use the comment lines in the config.py instead, I got:

init ['1']
main ['1']

So why does the difference happen? (Python 3.5.5)

Yulong Ao
  • 1,199
  • 1
  • 14
  • 22

1 Answers1

1

Once imported from config.py, the variable config becomes a separate copy of config.config that lives in main.py's namespace. You should import config as a module and then access the variable config as an attribute to the module config instead:

import config

def main():
    config.init_config()
    print("main", config.config)

if __name__ == '__main__':
    main()
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • Can you explain why the modified code by using list is OK? – Yulong Ao Jul 05 '18 at 03:29
  • This is because a list variable actually stores just a reference to the list, so when you import `config` as a list from the `config` module, even though you're making a copy of the `config` variable in the `config` module into `main.py`'s namespace, the copy of the value still has the reference to the same list in memory, so in this case modifying the list in the `config` module can still be accessed through the copy of the `config` variable in `main.py`. – blhsing Jul 05 '18 at 03:36