I have 2 files in same directory, a compiled library file and source file:
.
├── a.py
└── a.pyd
It looks like import a
that actually imports the a.pyd
module. But I can't find some official document guaranteeing that.
Does any one know about the import ordering of different file type?
This same question applies to Unix Python extensions (.so)
Thanks for wim's answer.
show the result
Although I cant see the order of pyd,py.
At least I can distinguish which one that I import to modular.
In a typical Python installation, the
ExtensionFileLoader
class has precedence over theSourceFileLoader
that is used for.py
files. It's theExtensionFileLoader
which handles imports of.pyd
files, and on a Windows machine you will find.pyd
registered inimportlib.machinery.EXTENSION_SUFFIXES
(note: on Linux/macOS it will have.so
in there instead).So in the case of name collision within same directory (which means a "tie" when looking through
sys.path
in order), thea.pyd
file takes precedence over thea.py
file. You may verify that when creating emptya.pyd
anda.py
files, the statementimport a
attempts the DLL load (and fails, of course).To see the precedence in the CPython sources, look here in
importlib._bootstrap_external. _get_supported_file_loaders
:For a doc reference, see http://www.python.org/doc/essays/packages/
This doc doesn't explicitly mention ".pyd", but that's the Windows equivalent of ".so". I've just tested on a Windows machine, and indeed
'.pyd'
appears before'.py'
in the suffix list.Note that the reference given above is very old! Since this essay was written, the import system has been completely revamped, and the underlying machinery exposed for users (you can mutate the
sys.meta_path
to register your own loaders or change precedence, for example). So it would be possible now to customize for '.py' to be preferred to '.pyd', and it doesn't matter much whatimp.get_suffixes()
has to say about anything (actually, that function is deprecated now). A default Python installation would not do that, of course, and the default precedence remains the same as the reference above has mentioned.