NB: I know the proper solution is just to do pip install pywin32 and let everything be done automatically, but here this question is about the internals of pythoncom.
When doing import pythoncom, it works, but:
in "C:\Python38\Lib\site-packages\pythoncom.py", there is
import pywintypes, but no pywintypes.py or .pyd or .dll is present in thesite-packagesdirectory. How can it "magically" findpywintypes?when doing
print(pythoncom.__file__), we see:'C:\\Python38\\lib\\site-packages\\pywin32_system32\\pythoncom38.dll'How is this stunning behaviour possible internally? (i.e. pythoncom.py that we imported is now recognized as another file, a .dll)
Also,
pythoncom.pycontains:# Magic utility that "redirects" to pythoncomxx.dll import pywintypes pywintypes.__import_pywin32_system_module__("pythoncom", globals())
What and where is this (I quote) "magic utility" that redirects to pythoncomxx.dll?
I don't see where this utility is called when doing just import pythoncom.
I believe the magic utility is
pywintypes.__import_pywin32_system_module__combined with_win32sysloader.The DLL path is built here (where modname is 'pythoncom'):
which gets passed to _win32sysloader:
which is a C++ file that loads the DLL:
The final result is the path of the loaded DLL, which gets registered as a Python module here:
As for why pywintypes, it should be under
Lib/site-packages/win32/lib/pywintypes.py. But if you actually import it you get another DLL path:But that's because
pywintypesuses its own__import_pywin32_system_module__function to replace itself:And finally, the reason that importing
pywintypesfromLib\site-packages\win32\libworks is due to the library'spywin32.pthfile (per @Jeronimo's comment), a path configuration file. This file is automatically imported at interpreter start, and the paths there are added to the import paths.