Search code examples
pythonpython-3.xpython-importsyspythonpath

Why sys.path.insert not using the latest python package?


List below is my project structure.

├── folder1
    ├── test.py
├── folder2
    ├── A.py
├── folder3
    ├── A.py

A.py in folder2 and folder3 are the same except self.key

#folder2
class TestAPI():
    def __init__(self):
        self.key = 50 


#folder3
class TestAPI():
    def __init__(self):
        self.key = 100  

In test.py, the code is

import sys
root_path = '/user/my_account'

sys.path.insert(0, root_path + '/folder2')
from A import TestAPI
test_api =  TestAPI()
print(test_api.key)

sys.path.insert(0, root_path + '/folder3')
from A import TestAPI
test_api = TestAPI()
print(test_api.key)
print(sys.path)

While executing test.py, it returns 50,50, ['/user/my_account/folder3', '/user/my_account/folder2']. Why the second time from A import TestAPI not from folder3 but folder2?

Edit: If I'd like to import TestAPI from folder3 for the second time, is there a way to 'delete' the PYTHONPATH after import TestAPI from folder2?


Solution

  • importlib.reload solve my question.

    import sys
    root_path = '/user/my_account'
    
    sys.path.insert(0, root_path + '/folder2')
    import A
    test_api =  A.TestAPI()
    print(test_api.key)
    
    sys.path.insert(0, root_path + '/folder3')
    import importlib
    importlib.reload(A)  # should reload after inserting PYTHONPATH and before import A
    
    import A
    test_api = A.TestAPI()
    print(test_api.key)
    print(sys.path)