I have a situation where the same Python module is present in the same directory in two different versions; mymodule.py
and mymodule.so
(I obtain the latter from the first via Cython, but that's irrelevant to my question). When from Python I do
import mymodule
it always chooses mymodule.so
. Sometimes I really want to import mymodule.py
instead. I could temporarily move mymodule.so
to another location, but that does not play well if I simultaneously have another Python instance running which needs to import mymodule.so
.
The question is how to make import
prefer .py
files over .so
, rather than vice versa?
Here's my thoughts on a solution:
I imagine performing some magic using importlib
and possibly edit sys.meta_path
. Specifically I see that sys.meta_path[2]
holds _frozen_importlib_external.PathFinder
which is used to import external modules, i.e. this is used for both mymodule.py
and mymodule.so
. If I could just replace this with a similar PathFinder
which used the reverse ordering for file types, I would have a solution.
I'm using Python 3.7, if that affects the solution.
Edit
Note that simply reading in the source lines of mymodule.py
and exec
'ing them won't do, as mymodule.py
may itself import other modules which again exist in both a .py
and .so
version (I want to import the .py
version of these as well).