Python - Import a file that is a symbolic link

If I have x.py and y.py files. And y.py is the link (symbolic or hard) x.py.

If I import both modules into my script. Whether he will import it once or he assumes that both are different files and import it twice.

What is he doing exactly?

+7
python import testing
source share
2 answers

Python will import it twice.

A link is a file system concept. For the Python interpreter, x.py and y.py are two different modules.

 $ echo print \ "importing \" + __file__> x.py
 $ ln -s x.py y.py
 $ python -c "import x; import y"
 importing x.py
 importing y.py
 $ python -c "import x; import y"
 importing x.pyc
 importing y.pyc
 $ ls -F * .py * .pyc
 x.py x.pyc y.py @ y.pyc
+9
source share

You need to be careful only if your script itself is a symbolic link, in which case the first sys.path entry will be the directory containing the link target.

+10
source share

All Articles