For your specific requirement , you can move the test()
function to another python file lets say test.py
, and then import it as -
from test import test
When python is trying to find the test.py
it consults the sys.path
(read PYTHONPATH) list , which contains the list of all directories inside which python will try to locate the test.py
.
Now when running a script, python automatically appends the current directory (from where the script is run) as the first element of sys.path (Please note this is not the location of the script, rather the location in command line/terminal from where the script was run) .
Then some standard libraries as well as the information in PYTHONPATH.
As an example , I had set my PYTHONPATH variable in windows to D:\\
and the sys.path
when my script was run from D:\Python\test\shared
was -
['D:\\Python\\test\\shared', 'C:\\Python34\\lib\\site-packages\\setuptools-17.1.1-py3.4.egg', 'C:\\Python34\\lib\\site-packages\\openpyxl-2.2.4-py3.4.egg', 'D:\\', 'C:\\windows\\system32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']
Now when trying to find test.py
, python will look through the above list sequentially (from first element to last) till test.py
is found, if not found will throw ImportError
, if found it loads the test.py
from the first location it found it in (it does not search in later directories , if it has been found once).
So in your case, you can keep the classic test.py
in some common location and then add that path to PYTHONPATH
, and then when you want to change the logic of test()
function , you can create a test.py
in your current directory with a test()
function containing the new logic, and when you run main.py
since test.py
exists in your current directory, that would be loaded (instead of the other test.py
)
But please note you should deal with this carefully, since I have seen lots of people getting different errors ,because they mess up their imports (having mutliple files with same name) and many of them present in the PYTHONPATH
variable.