It can be used when you want to import dynamically due to some special circumstances.
https://docs.python.org/ja/3/library/importlib.html
Everything is written in the document, but it's a little difficult to understand, so if you want to use it quickly, I think it's a good idea to put the following code in the beginning.
import importlib.machinery
import sys
class PackageFinder(importlib.machinery.PathFinder):
@classmethod
def find_spec(cls, fullname, path=None, target=None):
if not path:
path = []
#Specify the list of directories you want to find in path
path.append("/path/to/package/root")
return importlib.machinery.PathFinder.find_spec(fullname, path, target)
sys.meta_path.append(PackageFinder)
By dynamically switching the path of the above code, you can also do acrobatic things such as synchronously reading a specific directory, downloading and reading a remote directory (recommended). I don't have one).
In addition, there is also sys.path_hooks, so this seems to be used when you want to customize the behavior of the module import corresponding to it by taking the path as an argument instead of adding the path.
Recommended Posts