Python2中内置reload()重载修改后模块未生效的问题排查
reload() Isn't Working in Python 2 for Your Module Let’s break down what’s going wrong here, and how to fix it:
The Root Cause
Your reload(config) call in Python 2 isn’t taking effect because the config.py file ends up with invalid syntax after you append to it. Here’s the breakdown:
When create_config_file() writes the initial config.py, the final line is just ] with no trailing newline. Then, append_config_list() adds new code using append ('a') mode—this means the new LIST += [...] code gets tacked directly onto the end of the last line of the existing file, resulting in broken syntax like:
LIST = [ 'item1', 'item2', ]LIST += [ 'item3', ]
The ]LIST += [ part is invalid Python. When reload(config) tries to re-execute the module, it hits this syntax error and fails to update the module’s attributes. In Python 2, this might fail silently (or throw an error you didn’t notice), whereas Python 3’s importlib.reload() is stricter about reporting syntax issues.
Simple Fixes
You have two easy ways to fix this syntax problem:
Add a trailing newline when creating the initial file
Update yourcreate_config_file()function to include a newline at the end of the text:def create_config_file(): text = """LIST = [ 'item1', 'item2', ] """ # Extra newline at the end with open('config.py', 'w') as f: f.write(text)Prepend a newline when appending code
Adjustappend_config_list()to start the new text with a newline, ensuring the added code starts on a fresh line:def append_config_list(items): import config text = "\nLIST += [\n" # Start with a newline for item in items: if item not in config.LIST: text += " '{}',\n".format(item) text += "]\n" with open('config.py', 'a') as f: f.write(text)
Why Python 3 Worked
When you tested with Python 3’s importlib.reload(), you likely either fixed the newline issue accidentally, or Python 3’s reload mechanism is more aggressive about reporting syntax errors (which would have clued you in to the invalid code). Once config.py has valid syntax, both Python 2’s reload() and Python 3’s importlib.reload() will correctly update the module’s LIST attribute.
内容的提问来源于stack exchange,提问作者heinzel

