fork(1) download
  1. import os
  2. import sys
  3. import tempfile
  4. import importlib
  5.  
  6.  
  7. # Create some module and import it
  8. dir = tempfile.TemporaryDirectory()
  9. os.mkdir(os.path.join(dir.name, 'test_package'))
  10. with open(os.path.join(dir.name, '__init__.py'), "w") as f:
  11. f.write("\n")
  12. with open(os.path.join(dir.name, 'test_package', 'some_module.py'), "w") as f:
  13. f.write("def a():\n print(\"old\")\n return 0\n")
  14. sys.path.insert(0, dir.name)
  15.  
  16. from test_package import some_module
  17.  
  18. # Check that imported code works as expected
  19. assert some_module.a() == 0
  20.  
  21. # Alter module and reload
  22. with open(os.path.join(dir.name, 'test_package', 'some_module.py'), "w") as f:
  23. f.write("def a():\n print(\"new\")\n return 1\n")
  24.  
  25. importlib.reload(some_module)
  26.  
  27. # Check wether modifications have been reloaded
  28. assert some_module.a() == 1
  29.  
  30. sys.path.pop(0)
Runtime error #stdin #stdout #stderr 0.03s 47488KB
stdin
Standard input is empty
stdout
old
old
stderr
Traceback (most recent call last):
  File "./prog.py", line 28, in <module>
    assert some_module.a() == 1
AssertionError